使用 Processing 在 OoP 中围绕自己的轴旋转
Rotate around its own axis in OoP with Processing
我目前在编写 PROCESSING Sketch 时有点卡住了。假设我有一堆矩形像气泡一样在草图 window 上移动……它们有不同的大小和颜色……我想让它们在向上移动时绕着自己的轴旋转。我尝试使用 pushMatrix();和弹出矩阵(); – 甚至翻译();但我想它有点复杂,因为我在每个矩形的 X 和 Y 位置的构造函数中使用 OoP 和变量…
这是我草图的代码:
Rectangle[] rectangles = new Rectangle[10];
void setup() {
size(360, 640);
for (int i = 0; i < rectangles.length; i++) {
rectangles[i] = new Rectangle(random(0, width), random(20, 200), random(0, 250));
}
}
void draw() {
background(255);
for (int i = 0; i < rectangles.length; i++) {
rectangles[i].display();
rectangles[i].ascend();
rectangles[i].top();
}
}
Class 矩形是:
class Rectangle {
float x;
float y;
float speed;
float d;
float c;
Rectangle(float tempX, float tempD, float tempC) {
rectMode(CENTER);
x = tempX;
y = height + d/2;
d = tempD;
speed = random(0.5, 2.5);
c = tempC;
}
void display() {
noStroke();
fill(c);
rect(x, y, d, d);
}
void ascend() {
y = y - speed;
}
void top() {
if (y < -d/2) {
y = height + d/2;
}
}
}
这是我试过的,通常有效:
void display() {
noStroke();
fill(c);
pushMatrix();
translate(width/2, height/2);
rotate(radians(frameCount));
rect(x, y, d, d);
popMatrix();
}
如果有人知道或提示我遗漏了什么,我将非常感激!
感谢您提前提供任何帮助!
祝一切顺利!
原地旋转时,通常最有效的方法是使用 translate
将其绘制在“原点”。在您的情况下,这意味着您要翻译 rect()
的前两个参数均为零。所以你平移,然后旋转,然后“在原点”绘制矩形。
解决方案:
pushMatrix();
translate(x, y);
rotate(radians(frameCount));
rect(0, 0, d, d);
popMatrix();
我目前在编写 PROCESSING Sketch 时有点卡住了。假设我有一堆矩形像气泡一样在草图 window 上移动……它们有不同的大小和颜色……我想让它们在向上移动时绕着自己的轴旋转。我尝试使用 pushMatrix();和弹出矩阵(); – 甚至翻译();但我想它有点复杂,因为我在每个矩形的 X 和 Y 位置的构造函数中使用 OoP 和变量…
这是我草图的代码:
Rectangle[] rectangles = new Rectangle[10];
void setup() {
size(360, 640);
for (int i = 0; i < rectangles.length; i++) {
rectangles[i] = new Rectangle(random(0, width), random(20, 200), random(0, 250));
}
}
void draw() {
background(255);
for (int i = 0; i < rectangles.length; i++) {
rectangles[i].display();
rectangles[i].ascend();
rectangles[i].top();
}
}
Class 矩形是:
class Rectangle {
float x;
float y;
float speed;
float d;
float c;
Rectangle(float tempX, float tempD, float tempC) {
rectMode(CENTER);
x = tempX;
y = height + d/2;
d = tempD;
speed = random(0.5, 2.5);
c = tempC;
}
void display() {
noStroke();
fill(c);
rect(x, y, d, d);
}
void ascend() {
y = y - speed;
}
void top() {
if (y < -d/2) {
y = height + d/2;
}
}
}
这是我试过的,通常有效:
void display() {
noStroke();
fill(c);
pushMatrix();
translate(width/2, height/2);
rotate(radians(frameCount));
rect(x, y, d, d);
popMatrix();
}
如果有人知道或提示我遗漏了什么,我将非常感激! 感谢您提前提供任何帮助!
祝一切顺利!
原地旋转时,通常最有效的方法是使用 translate
将其绘制在“原点”。在您的情况下,这意味着您要翻译 rect()
的前两个参数均为零。所以你平移,然后旋转,然后“在原点”绘制矩形。
解决方案:
pushMatrix();
translate(x, y);
rotate(radians(frameCount));
rect(0, 0, d, d);
popMatrix();