[SOLVED] Using the keyboard to change the direction a moving circle

Hello,

I am trying to write a program that causes the circle to go in one direction but when I press the letter ‘a’ on the keyboard it will go the opposite direction. Additionally, if the circle reaches a boundary it will go the opposite direction. My issue is when I press the letter ‘a’ on my keyboard it only changes direction sometimes. I was trying to accomplish this by using an if statement. I have attached my code below. Any help would be greatly appreciated,

float x=300;
float y=400;

void setup() {
  size(850, 950);
  background(100);
}

void draw() {


  noStroke();

  ellipse(x, y, 50, 50);
  fill(0, random(155), random(255));
  x=x+Speed;


  if ((keyPressed == true) && (key == 'a')||x > width||x < 0) {
    Speed=Speed*-1;
  }

}

1 Like

Hello,

Welcome to community!

Consider the following:

  1. Declare a global variable for Speed. The example does not do this.
  2. One if statement for just the boundaries inside draw().
  3. Using keyPressed():
    keyPressed() / Reference / Processing.org

The keyPressed() function is called once every time a key is pressed.

  1. Use println() for seeing the status of variables in your code:
    println() / Reference / Processing.org

This will demonstrate that key is detected multiple times:

  if ((keyPressed == true) && (key == 'a')||x > width||x < 0) {
    Speed=Speed*-1;
    print(char(key));
    }

:slight_smile:

1 Like

Hello,

Thank you for your help! The code is now working after implementing your suggestions. The biggest issue seems to have been that there was not a keyPressed () function.

1 Like