java - 我如何使代码中的线条在 Canvas 的墙壁之间反弹?

标签 java processing

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

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

最佳答案

你需要值(value)观。线的当前x坐标和移动:

float tx = 0;
float dx = 40;

每次line线到达窗口的左侧或右侧时,再改变方向:

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

关于java - 我如何使代码中的线条在 Canvas 的墙壁之间反弹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61168079/

相关文章:

java - 从字符串中删除字符

java - 如何制作正在处理的游戏首页?

processing - 如何将位置对齐到矩形网格?

java - 如何返回处理中矩形边界内的任意点?

java - Kryonet,无法发送 BufferedImage

java - spring中的空字符串表单输入

javascript - 在 Javascript 中使用渐变方向来引导笔触效果

arduino - 处理 RGB 轮来控制 Arduino RGB LED

java - 分配新对象是否会自动销毁先前分配给同一数据成员的对象?

java - 排除Java项目中的特定警告