如何在处理过程中按键盘上的任意键改变球的运动?

How can I change the movement of the ball on pressing any keys from the keyboard in processing?

下面是我在处理过程中使用的代码。我希望编辑代码以更改 canvas 上的椭圆在按键盘上的任意键时的移动。

        float circleX = 0;
        float circleY = 0;
        
        float xSpeed = 2.5;
        float ySpeed = 2;
        
        void setup() {
         size(500, 500); 
        }
        
        void draw() {
          background(0,200,0);
        
          circleX += xSpeed;
          if (circleX < 0 || circleX > width) {
            xSpeed *= -1;
          }
        
          circleY += ySpeed;
          if (circleY < 0 || circleY > height) {
            ySpeed *= -1;
          }
        
          ellipse(circleX, circleY, 100, 100);
        }

   

您可以使用 in-built keyPressed 函数来处理用户输入,因此您可以在原始代码之后添加:

void keyPressed() {
  switch (keyCode) { // the keyCode variable is used to identify which non-ASCII key was pressed
    case LEFT:
      xSpeed -= 0.1;
      break;
    case RIGHT:
      xSpeed += 0.1;
      break;
    case UP:
      ySpeed -= 0.1;
      break;
    case DOWN:
      ySpeed += 0.1;
      break;
    default: // default is used when none of these are pressed, so in this case it is when any key is pressed
      // this depends on what you want to do, but in this case I am just inverting the speed, so replace as you see fit
      xSpeed *= -1;
      ySpeed *= -1;
  }
}

希望对您有所帮助!