xxxxxxxxxx
73
// @AminAhmadAhmadi
// Coding Challenge #2: Menger Sponge Fractal
// https://youtu.be/LG8ZK-rRkXo
var rx = 15;
var ry=15;
var sponge = [];
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
normalMaterial();
b = new Box(0, 0, 0, 400)
sponge.push(b);
}
function draw() {
background(51);
rx=map(mouseY,0,height,1.5,-1.5);
ry=map(mouseX,0,width,-1.5,1.5);
rotateX(rx);
rotateY(ry);
sponge.forEach(p => p.show());
}
function mousePressed() {
var next = [];
sponge.forEach(t => {
var new_boxes = t.generate();
next = next.concat(new_boxes);
});
sponge = next;
}
function Box(x_, y_, z_, r_) {
this.pos = createVector(x_, y_, z_);
this.r = r_;
this.show = () => {
push();
translate(this.pos.x, this.pos.y, this.pos.z);
box(r_);
pop();
}
this.generate = () => {
var Boxes = []
for (let x = -2; x < 3; x++) {
for (let y = -2; y < 3; y++) {
for (let z = -2; z < 3; z++) {
let sum = abs(x) + abs(y) + abs(z);
let newR = this.r / 5;
if (sum > 3 ) {
b = new Box(
this.pos.x + x * newR,
this.pos.y + y * newR,
this.pos.z + z * newR,
newR);
Boxes.push(b);
}
}
}
}
return Boxes;
}
}