我正在使用处理程序,目前正在尝试使矩形逐步移动(特别是8步移动),但是我遇到了麻烦。有人可以帮我吗?
//Declare variables
int x = 0;
int dx = 1;
boolean move = true;
void setup() {
//Set screen size
size (1280, 720);
}
void draw() {
//Set Background to white
background (240, 240, 240);
fill(255, 147, 79);
noStroke();
rectMode(CORNER);
//Draw the rectangle
rect(0, x, width/14.22, height/8);
//IF statement that will only run if the move variable is true
if (move == true) {
//Set the x variable to current x value plus the value of the dx variable
x = x + dx;
//IF statement that will only run if the x variable is larger then height - height/8
if (x > height - height/8) {
//Set dx to -1
dx = -1;
}
//IF statement that will only run if the x variable minus 10 is less then 0
if (x < 0) {
//Set dx to -1
dx = 1;
}
}
}
void keyPressed() {
//IF statement that will only run if keyCode variable is equal to 32 (SpaceBar)
if (keyCode == 32) {
//Flip the move variable
move = !move;
}
}
如果矩形应为正方形,并且应为窗口高度的八分之一,则高度为height/8
,宽度与高度相同:
rect(0, y, height/8, height/8);
如果矩形应以8步上下移动,则使用步骤索引step_i
。矩形的y
坐标取决于索引:
int y = step_i*height/8;
rect(0, y, height/8, height/8);
如果索引为<= 0或> = 7则更改方向:
step_i += dy;
if (step_i <= 0 || step_i >= 7) {
dy *= -1;
}
示例代码:
int dy = 1;
int step_i = 0;
void draw() {
//Set Background to white
background (240, 240, 240);
fill(255, 147, 79);
noStroke();
rectMode(CORNER);
//Draw the rectangle
int y = step_i*height/8;
rect(0, y, height/8, height/8);
//IF statement that will only run if the move variable is true
if (move == true) {
step_i += dy;
if (step_i <= 0 || step_i >= 7) {
dy *= -1;
}
}
}