Search code examples
processing

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


Below is the code I am working with in processing. I want the code to be edited to change the movement of the ellipse on the canvas on pressing any key from the keyboard.

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

   

Solution

  • You can use the in-built keyPressed function to handle user input, so after your original code, you could add this:

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

    Hope this helps!