我几乎让这个 p5.js“艺术品”工作了。但我不确定为什么他们都停留在某一时刻。 我以类格式编写它们,并检查了代码,但找不到导致它的任何错误。谢谢
没有太多要添加的细节,抱歉没有太多细节要添加,抱歉没有太多细节要添加,抱歉没有太多细节要添加,抱歉没有太多细节要添加,抱歉没有太多细节要添加,抱歉没有太多细节要添加,抱歉没有太多细节添加抱歉没有太多细节添加抱歉
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>
最佳答案
您必须按 translate()
设置翻译将每个立方体放在其位置。
请注意,诸如 translate()
和 rotate()
之类的操作定义一个矩阵并将当前矩阵乘以新矩阵。因此,您必须通过 push()
存储当前矩阵,在更改立方体的模型矩阵之前。绘制立方体后,您必须通过 pop()
恢复矩阵:
class class_Cube {
// [...]
update() {
push()
translate(this.x, this.y)
this.rotate();
this.cubes();
pop();
}
// [...]
}
参见示例:
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>
关于javascript - p5.js 形状循环错误(全部卡在一点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62357650/