我必须让一个盒子将锯齿形移动到屏幕底部。我想出了如何使该框从左上角开始,移至右上角,然后向下移动(一个完整的(x,y,90,90)框)。我之所以陷入困境,是因为我意识到我要编写的下一个if语句正在与第一个if语句抗争,以将框滑到屏幕的左端。我已经尝试了一段时间和循环来解决此问题,但老实说,我不知道该做什么或在哪里做。我需要程序在屏幕上一直执行此操作,然后停止(810,810,90,90)并停止。有什么建议吗?
这是我的主要代码:
WBox v1;
int a = 0;
float x=0;
float y=0;
void setup() {
size(900, 900);
frameRate(1000);
v1 = new WBox();
}
void draw(){
background(255);
fill(0);
rect(x,y,90,90);
if(x<810){
x+=1;
} else if(y < 90){
y+=1;
} else if (x<=0){
x-=1;
}
}
这里是班级:** WBox类{PVector wb;
void box(int tempX, int tempY) {
wb = new PVector(tempX, tempY);
wb.mult(a);//
rect(wb.x, wb.y, 90, 90);
}
}
完全免责声明:更好的做法是,以不同的方式使用WBox类来实现这一目标,但是您似乎是一个初学者,我将坚持简单的做法。如果您愿意,可以问我一个问题,我会待一会儿。
而不是使用运动速度的硬编码数字,让我们尝试使用变量:
float boxSpeedX = 1;
我们只需要弄清楚一种算法就可以解决它。最好的方法是使用伪代码。
换句话说:在机器代码后写逻辑。像这样的东西:
似乎很容易。让我们更接近代码:
if (reached a border)
box move horizontally toward the other border
else
box move downward 90 pixels
if (box reached (810, 810)
stop
Closer!
// let's start with the stop condition
if (box reached 810, 810)
do nothing
else
if (box is on an horizontal line)
x += speed
if (box reached right side)
speed = -1 // so next time it'll go left
y +=1 // this way the box isn't on an horizontal line anymore
else if (box reached left side)
speed = 1
y += 1
else
y += 1
现在让我们详细说明一些细节:
(box is on an horizontal line):
horizontal lines are multiples of 90 pixels
(box reached right side)
x == 810
(box reached left side)
x == 0
我们将使用modulo operator来知道y的数字是90的倍数还是90。要花一些时间来理解该运算符,它确实非常有用。简而言之,它将为您提供整数除法的余数(例如,如果您执行13/5,则整数除法将显示为“ 2”,而模数将显示为“ 3”,而不是用小数表示小数,因为存在2乘以13中的5,而不是“满5”,此操作后剩下3个单位)。
我觉得我们现在已经足够接近了。剩下的只是在代码中翻译它。我为您做了,我在代码中留下了注释。您可以将其复制并粘贴到Processing IDE中,然后它将运行。您可以在此示例的基础上,让自己的盒子做任何您想做的事情。
WBox v1;
int a = 0;
float x=0;
float y=0;
float boxSpeedX = 1;
void setup() {
size(900, 900);
frameRate(1000);
v1 = new WBox();
}
void draw() {
background(255);
fill(0);
rect(x, y, 90, 90);
moveBox();
}
void moveBox() {
// first check for the stop condition:
if (x != 810 || y != 810) { // the box will move only while the stop condition isn't met
// if the box is on a horizontal line, let's move it
if (y % 90 == 0) { // the '%' operator's name is 'modulo', it's awesome and useful
x += boxSpeedX;
// once the box has moved, let's check if we need to steer it down:
if (x == 0) { // if the box reaches the left side
boxSpeedX = 1; //next time the box moves horizontally, it'll go right
y += 1; // let's move down
} else if (x == 810) {
boxSpeedX = -1;
y += 1;
}
} else { // if the box isn't on an horizontal line, let's move it downward until it reaches a new line
y += 1;
}
}
}
class WBox {
PVector wb;
void box(int tempX, int tempY) {
wb = new PVector(tempX, tempY);
wb.mult(a);//
rect(wb.x, wb.y, 90, 90);
}
}
玩得开心!