这是一个伟大的时刻使用面向对象的编程!如果我正确地理解了这个问题,您希望每个立方体独立于其他立方体旋转。我们来创建一个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网站获得this tutorial。我将一些概念引入了Cube类。
由于您希望在屏幕上绘制多个立方体,因此我们创建一个立方体数组。我选择了25作为任意数字。
Cube[] cube = new Cube[25];
现在setup()
,我们需要实际创建每个立方,并给它一定的参数,如在屏幕上的位置,颜色等。以下是这是如何实现的。
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()
}
这是整个程序。每次通过draw()
循环呼叫background()
非常重要,因此显示窗口将在每帧中清除。评论一下,看看会发生什么,但我注意到这不在你上面提供的代码片段中。我想这可能是一种效果!
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语言)非常有帮助,所以我建议this OOP tutorial从处理的网站,如果你需要一个速成课程。当OOP最终有意义时,我的编程生活发生了变化。
我唯一的编程经验是Max/MSP和编程微控制器,从来没有真正完全理解OOP,但我现在明白了。谢谢! – snarehanger 2013-05-12 20:59:47