首页 > 解决方案 > 如何使代码中的线条在画布的墙壁之间反弹?

问题描述

我正在使用处理,我试图让矩形在碰到屏幕一侧时反转其方向。具体来说,当矩形的边缘到达窗口的一侧时,矩形应该改变方向并开始向另一侧移动,而不是仍然向右移动。当它撞到窗户的另一侧时,方向应该再次反转。

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;
  }

标签: javaprocessing

解决方案


你需要价值观。直线的当前 x 坐标和运动:

float tx = 0;
float dx = 40;

每当线条到达窗口的左侧或右侧时,改变方向:

tx += dx;
if (tx < 0 || tx >= width) {
    dx *= -1;
}

示例代码:

long lastTime = 0;
long lastTimeEllipse = 0;
float tx = 0;
float dx = 40;

void setup() {
    size(400, 200);
    frameRate(60);
    lastTime = millis();
    lastTimeEllipse = millis();
}

void draw() {
    background(0);
    if ( millis() - lastTime > 500) {
        lastTime = millis();
        tx += dx;
        if (tx < 0 || tx >= width) {
            dx *= -1;
        }
    }
    stroke(255, 0, 0);
    line(tx, 0, tx, height);
}

推荐阅读