我将如何在垂直堆栈中绘制4个正方形,使用循环来回移动,以避免在绘制4个正方形时重复相同的代码4次。正方形应移动为一个,当它们中的任何一个碰到窗口的边缘时,它们都将改变方向。
float location;
float sizeWidth;
float sizeHeight;
float direction;
boolean moving;
void setup() {
size (1280, 720);
location = 0;
direction = height/720;
sizeWidth = 90;
sizeHeight = 90;
moving = true;
}
void draw() {
background(255);
stroke(0);
strokeWeight(1);
for (int i = 0; i < width; i = i + 90) {
line(0, i, 1280, i);
line(i, 0, i, 720);
}
fill (255, 147, 79);
int steppedPos = (int)(location/sizeHeight+0.5);
rect(0, steppedPos*sizeHeight, sizeWidth, sizeHeight);
if (moving) {
location = location + direction;
if (location + sizeHeight > height || location < 0){
direction = direction * -1;
location = location + direction;
}
}
}
void keyPressed() {
if (key == ' ') {
moving = !moving;
}
}
创建class
class
,而不是单个变量Square
,location
,sizeWidth
和sizeHeight
:
direction
为正方形添加数组变量:
class Square {
float locationX;
float locationY;
float sizeWidth;
float sizeHeight;
float direction;
color col;
Square(float x, float y, float w, float h, float d, color c) {
locationX = x;
locationY = y;
sizeWidth = w;
sizeHeight = h;
direction = d;
col = c;
}
// [...]
}
在Square squares[];
中创建正方形:
for
-loop
[添加可以绘制Square对象的方法:
for
循环绘制正方形:
void setup() {
// [...]
squares = new Square[4];
for (int i = 0; i < squares.length; ++i ) {
squares[i] = new Square(i*90, 0, 90, 90, height/720, color(255, 147, 79));
}
}
[添加移动Square对象的方法:
class Square {
// [...]
void Draw() {
fill(col);
int steppedPosX = (int)(locationX/sizeWidth+0.5);
int steppedPosY = (int)(locationY/sizeHeight+0.5);
rect(steppedPosX*sizeWidth, steppedPosY*sizeHeight, sizeWidth, sizeHeight);
}
}
循环移动方块:
void draw() {
// [...]
for (int i = 0; i < squares.length; ++i ) {
squares[i].Draw();
}
// [...]
}
请参见示例:
class Square {
// [...]
void Move() {
locationY = locationY + direction;
if (locationY + sizeHeight > height || locationY < 0){
direction = direction * -1;
locationY = locationY + direction;
}
}
}
void draw() {
// [...]
if (moving) {
for (int i = 0; i < squares.length; ++i ) {
squares[i].Move();
}
}
}
查看星期一的演讲!我们完全涵盖了这一点。