有没有办法通过 keyPressed 使移动变量停止处理

Is there a way to make a moving variable stop in processing through keyPressed

我有一个任务,它期望一个变量在屏幕上持续移动,并在到达 x 轴末端后反弹(我已经完成了这部分)。但它也需要变量在按下键后停止移动......我知道我需要使用 keyPressed 但我不确定如何去做。一些朋友告诉我使用布尔变量,但我不确定如何将其引入代码中。

使用布尔变量最简单的方法是在 if 语句中。如果你有一个布尔变量x,你可以这样写

if (x) {
  //however you coded your ball's movement
}

x为真时,球会移动。当 x 为假时,球不会移动。之后,就是根据按键改变x的问题了。

在这里,我使用了布尔变量 isMoving 来跟踪是否按下了某个键。那么球的位置只有在这个布尔值为真时才会更新,如果按下一个键,布尔值就会更新。

boolean isMoving = true;

// The position of the ball
int x = 500;
int y = 500;

// The speed of the ball
int x_inc = 2;
int y_inc = 3;

int diameter = 50;

void setup(){
  size(1000, 1000);
}

void draw(){
  background(0);
  
  if(isMoving){
    // Update ball position
    x += x_inc;
    y += y_inc;
    
    // Reverse direction for x axis
    if(x + diameter/2 >= width || x -diameter/2 <= 0){
        x_inc *= -1;
    }
  
    // Reverse direction for y axis
    if(y + diameter/2 >= height || y-diameter/2 <= 0){
        y_inc *= -1;
    }
  }
  
  circle(x, y, diameter);
}

void keyPressed(){
  // Update boolean value
  isMoving = !isMoving;
}