Trying To Make A Circle Move Back and Forth On A Horizontal Line

//Constants
final int X_LEFT = 100;  //The left end of the horizontal line.
final int X_RIGHT = 400; //The right end of the horizontal line.
final int Y = 100; //The y position of the line and circle.
final int BALL_DIAM = 50; //The diameter of the circle
final float BALL_SPEED = 2.5; //Its speed (pixels/second)

//Variables 
float ballX = 100;
int reverseBall;
boolean ballRight = true;
boolean ballLeft = true;

void setup(){
  size(500,200); 
}

void draw(){
  background(200);
  moveBall();
  //drawAll();
}

void moveBall(){
  
  reverseBall = -1;
  ballX = ballX + BALL_SPEED;
  
  if(ballLeft){
    if(ballX == X_RIGHT || ballX == X_LEFT){
   ballX = ballX + (BALL_SPEED * reverseBall) ;
   
  }
}
   circle(ballX, Y, BALL_DIAM);
  line(X_LEFT, Y, X_RIGHT, Y);
}

So above is some code I’m working on and I can’t seems to get the coding just right to where the circle moves back and forth along a horizontal line. Additionally, I need to figure out how to stop the circle from moving back and forth when the mouse is pressed. I’m extremely new to coding and have been trying anything I’ve read up on or watched via youtube, but they all reference speed as variable and not a constant. I need to use a constant for this code so the conditional for mousePressed option is true, but I’m not sure how to set it up properly. I would greatly appreciate some extra assistance.

Without giving you the answers, here are some tips:

  • ballLeft is always true, so whatever is after that if will always be called…?
  • You have the right idea with ballX = ballX + BALL_SPEED; , and you can use mousePressed inside of an if
  • BALL_SPEED = BALL_SPEED * -1 can be used to reverse your speed
2 Likes