这是使用面向对象编程的好时机!如果我正确理解了这个问题,您希望每个立方体独立于其他立方体旋转。让我们创建一个 Cube 类。将每个立方体视为我们将单独处理的对象。
class Cube {
float x, y, z; // position of the cube
float size; // size of cube
color c; // color of cube
float xAngle, yAngle, zAngle; // current rotation amount of cube's x, y, z axes
float xSpeed, ySpeed, zSpeed; // how quickly the cube is rotated in the x, y, z axes
// Cube constructor - create the cube and all of its parameters
Cube(float x_, float y_, float z_, float size_, color c_, float xSpeed_, float ySpeed_, float zSpeed_) {
x = x_;
y = y_;
z = z_;
size = size_;
c = c_;
xSpeed = xSpeed_;
ySpeed = ySpeed_;
zSpeed = zSpeed_;
xAngle = yAngle = zAngle = 0; // starting position
}
// update the cube
// all we're doing is rotating each axis
void update() {
xAngle += xSpeed;
yAngle += ySpeed;
zAngle += zSpeed;
}
// draw the cube to the screen
void display() {
pushMatrix(); // need this
translate(x, y, z); // position on screen
rotateX(xAngle); // rotation amounts
rotateY(yAngle);
rotateZ(zAngle);
fill(c);
noStroke();
box(size);
popMatrix(); // and this
// push and pop matrix allows for individual cube rotation
// otherwise you would rotate the whole draw window, which isn't what you're looking for
}
}
如果您希望每个立方体在屏幕上更改颜色和位置但仍独立旋转,则该display()
函数可能是这样的:
void display() {
pushMatrix();
translate(random(0, width), random(0, height), random(-100, 100)); // random position on screen
rotateX(xAngle);
rotateY(yAngle);
rotateZ(zAngle);
fill(random(255), random(255), random(255), 50); // random color
noStroke();
box(size);
popMatrix();
}
理解 Processing 中元素的旋转和平移是非常关键的。如果您尚未阅读,我强烈推荐Processing 网站上的本教程。我在 Cube 类中加入了一些概念。
由于您想在屏幕上绘制多个 Cube,让我们制作一组 Cube。我选择了 25 作为任意数字。
Cube[] cube = new Cube[25];
现在setup()
,我们需要实际创建每个 Cube 并为其提供某些参数,例如屏幕上的位置、颜色等。这是如何完成的。
for (int i = 0; i < cube.length; i++) {
cube[i] = new Cube(random(0, width), random(0, height), 0, // x, y, z position
random(30, 80), color(random(255), random(255), random(255), 50), // size, color
random(0.001, 0.020), random(0.001, 0.020), random(0.001, 0.020)); // xSpeed, ySpeed, zSpeed
}
现在我们只需要将立方体绘制到屏幕上并更新每个立方体的旋转,这只是在draw()
循环中发生。
for (int i = 0; i < cube.length; i++) {
cube[i].update();
cube[i].display()
}
这是整个程序。background()
每次通过循环调用很重要,draw()
因此显示窗口将在每一帧中被清除。将其注释掉以查看会发生什么,但我注意到您在上面提供的代码片段中没有。我想这可能是一个效果!
Cube[] cube = new Cube[25];
void setup() {
size(640, 320, P3D);
smooth();
frameRate(60);
for (int i = 0; i < cube.length; i++) {
cube[i] = new Cube(random(0, width), random(0, height), 0,
random(30, 80), color(random(255), random(255), random(255), 50),
random(0.001, 0.020), random(0.001, 0.020), random(0.001, 0.020));
}
}
void draw() {
camera();
lights();
background(50);
for (int i = 0; i < cube.length; i++) {
cube[i].update();
cube[i].display();
}
}
我不确定你的编程背景是什么,但是掌握面向对象编程的窍门对处理(和其他 OOP 语言)非常有帮助,所以如果你需要速成课程,我会推荐Processing 网站上的这个 OOP 教程。当 OOP 终于变得有意义时,我的编程生活发生了变化。