【发布时间】:2023-01-27 18:35:17
【问题描述】:
这是我的 p5.js 类中的一个项目。 我有一个创建 3D 形状的类,我在 for 循环的绘制函数中调用它。在这个 for 循环中,我创建了形状并且它有一个旋转。如果我按下“a”按钮,它会创建一个新形状。我的问题是,我想在创建新形状时停止先前形状的旋转,但我找不到解决方案。
这是我的代码:
` let BLACK;
let GRAY;
let LIGHTGRAY;
let WHITE;
let RED;
let forms = \[\];
let coorX, coorY, coorZ, colour;
let COL = \[\];
let ran;
function setup() {
createCanvas(586, 810, WEBGL);
BLACK = color(0);
GRAY = color(70);
LIGHTGRAY = color(180);
WHITE = color(255);
RED = color(217,4,33);
COL = \[BLACK, WHITE, GRAY, RED, RED\]
ran = random(0.01,0.1)
}
function draw() {
background(80);
pointLight(250, 250, 250, 250);
for (let i = 0; i \< forms.length; i++) {
newSpeed = 0.05 + i \* ran
forms\[i\].create(newSpeed, 0.01);
if (forms.length \> 1){
rotateX(0);
}
}
if (forms.length \> 10){
//Array limited on 10 objects
forms.splice(0,1)
}
}
function keyTyped() {
if (key === 'a'){
coorX = int(random(-100,100))
coorY = int(random(-100,100))
coorZ = int(random(-200,200))
forms.push(new Shape(coorX, coorY, coorZ));
}
if (key === 'd'){
forms.pop()
}
}
class Shape {
constructor(posX, posY, posZ, colour){
this.x = 50; //width
this.y = 50; //height
this.z = 50; // depth
this.x1 = 0;
this.y1 = 500;
this.z1 = 80;
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
this.rand = int(random(0,5));
this.colour = colour;
}
create (speed, rotation){
//create a new shape
stroke(0);
strokeWeight(0);
push();
translate(this.posX, this.posY, this.posZ)
//rotate the shape
this.speed = speed;
this.rotation = rotation;
rotateX((frameCount \* this.rotation) \* speed)
rotateY((frameCount \* this.rotation) \* speed)
if (this.rand == 1){
fill(RED)
box(50,50,50)
}if(this.rand == 2) {
fill(LIGHTGRAY);
sphere(50,10)
}if(this.rand == 3){
fill(WHITE);
cylinder(5,280,15)
}if(this.rand == 4){
fill(GRAY);
torus(90,24,3)
}
pop();
}
}`
我尝试将旋转和创建功能分开,但随后它旋转了整个画布,而不是单独旋转了形状。
【问题讨论】:
-
请修复您的代码格式。
标签: arrays rotation processing p5.js