How to make the ball move left and right in java?

Assuming the method below is connected to the main method, which creates a circle in the window, and that I want this circle to move about 100 pixels to the left, and then move 100 pixels, etc.

I can not understand the code to do this.

  private void moveBall() 
{
    boolean moveRight = true;

    if(moveRight == true)
    {
        x = x + 1;
    }
    else
    {
        x = x - 1;
    }

    if(x == 300)
    {
        moveRight = false;
    }




}
+4
source share
1 answer

The reason the ball constantly moves to the right is because when it gets into the if statement to set moveRight to false, it returns true to true at the beginning of the method. You need to pull moveRightas a class variable if you want it to work the way you think.

How about this?

//set the moveRight variable as a class variable
private boolean moveRight = true;

private void moveBall() {
    //move right or left accordingly
    x = moveRight ? x + 1 : x - 1;

    //if x == 300 we want to move left, else if x == 100 im assuming you want to move right again
    if (x == 300) {
        moveRight = false;
    } else if(x == 100){
        moveRight = true;
    }
}
+1

Source: https://habr.com/ru/post/1619281/


All Articles