我正在使用处理程序,我试图使矩形在碰到屏幕侧面时反转其方向。具体来说,当矩形的边缘到达窗口的一侧时,矩形应改变方向并开始向另一侧移动,而不是继续向右移动。碰到窗户的另一侧时,方向应再次反转。
ArrayList<Ball> balls;
int rectWidth = 20;
int rectHeight = 20;
long lastTime = 0;
long lastTimeEllipse = 0;
float tx = 0; //x value TimeLine
float tx1 = 0; //x value Ellipse
float value = 0;
void setup() {
size(400, 200);
frameRate(60);
balls = new ArrayList();
lastTime = millis();
lastTimeEllipse = millis();
}
void draw() {
background(0);
if ( millis() - lastTime > 500) {
lastTime = millis();
//after 0.5 sec. tx moves 40px to the right
tx += 40;
value = 2;
} else if (millis()-lastTime < 500) {
value = 1;
}
stroke(255, 0, 0);
line(tx, 0, tx, height);
if (tx>=width) {
tx=0;
tx1 = tx1 + width;
}
您需要创建一个浮点数speed
(或类似的东西),并更改每次矩形的x(我猜是tx
?)小于0或大于width - rectWidth
。
因此,以draw
方法移动矩形后,请执行:
if(tx <= 0 || tx >= width - rectWidth)
speed = - speed;
您需要重视。线和运动的当前x坐标:
long lastTime = 0;
long lastTimeEllipse = 0;
float tx = 0;
float dx = 40;
void setup() {
size(400, 200);
frameRate(60);
//balls = new ArrayList();
lastTime = millis();
lastTimeEllipse = millis();
}
void draw() {
background(0);
if ( millis() - lastTime > 500) {
lastTime = millis();
tx += dx;
if (tx >= width || tx < 0) {
dx *= -1;
}
}
stroke(255, 0, 0);
line(tx, 0, tx, height);
}
```