Search code examples
processing

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


I have an assignment, it expects a variable to be moved across the screen consistently, and bounce back once it reaches the end of the x-axis (I've done this part). But it also needs the variable to stop moving once a key is pressed... I understand I need to use keyPressed but I'm unsure of how to do it. Some friends told me to use a Boolean variable but I'm not entirely certain how to introduce it into the code.


Solution

  • Here, I have used the boolean variable isMoving to keep track of whether a key has been pressed or not. Then the position of the ball is only updated if this boolean value is true and if a key is pressed, the boolean value is updated.

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