Reputation: 384
I almost got this p5.js 'artwork' working. but i am not sure why they all stuck at one point. I wrote them in class format and i checked through the codes but can't find any error that cause it. thanks
not much details to add sorrynot much details to add sorrynot much details to add sorrynot much details to add sorrynot much details to add sorrynot much details to add sorrynot much details to add sorrynot much details to add sorrynot much details to add sorrynot much details to add sorry
cubic = [];
function setup(){
createCanvas(windowWidth, windowHeight, WEBGL);
back = color(22,22,22);
for (let i = 0; i < 5; i++) {
let looper = map(i, 0, 4, 100, width - 100);
cubic.push(new class_Cube(looper, 0) );
}
}
function draw(){
background(back);
for (let j = 0; j < cubic.length; j++) {
cubic[j].update();
}
}
function mouseClicked() {
cubic = [];
for (let i = 0; i < 5; i++) {
let looper = map(i, 0, 4, 100, width - 100);
cubic.push(new class_Cube(looper, height/2) );
}
}
class class_Cube {
constructor(x,y) {
this.x = x;
this.y = y;
//cube values
this.size = 50;
this.stroke = 255;
//rotation
this.randX = random(0,360);
this.randY = random(0,360);
}
update() {
this.cubes();
this.rotate();
}
cubes() {
push();
noFill();
stroke(this.stroke);
box(this.size);
pop();
}
rotate() {
rotateX(this.randX);
rotateY(this.randY);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
Upvotes: 2
Views: 116
Reputation: 210889
You have to set a translation by translate()
to put each cube at its position.
Note, operations like translate()
and rotate()
define a matrix and multiply the current matrix by the new matrix. Hence you have to store the current matrix by push()
, before you change the model matrix of the cube. After you have drawn the cube, you have to restore the matrix by pop()
:
class class_Cube {
// [...]
update() {
push()
translate(this.x, this.y)
this.rotate();
this.cubes();
pop();
}
// [...]
}
See the example:
cubic = [];
function setup(){
createCanvas(windowWidth, windowHeight, WEBGL);
back = color(22,22,22);
for (let i = 0; i < 5; i++) {
let looper = map(i, 0, 4, -width/2 + 100, width/2 - 100);
cubic.push(new class_Cube(looper, 0) );
}
}
function draw(){
background(back);
for (let j = 0; j < cubic.length; j++) {
cubic[j].update();
}
}
function mouseClicked() {
cubic = [];
for (let i = 0; i < 5; i++) {
let looper = map(i, 0, 4, 0, width-10);
cubic.push(new class_Cube(looper, height/2) );
}
}
class class_Cube {
constructor(x,y) {
this.x = x;
this.y = y;
//cube values
this.size = 50;
this.stroke = 255;
//rotation
this.randX = random(0,360);
this.randY = random(0,360);
}
update() {
push()
translate(this.x, this.y)
this.rotate();
this.cubes();
pop();
}
cubes() {
push();
noFill();
stroke(this.stroke);
box(this.size);
pop();
}
rotate() {
rotateX(this.randX);
rotateY(this.randY);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
Upvotes: 2