Search code examples
javaandroidlibgdx

Android libgdx... moving of sprite back and forth horizontally


I don't know what's wrong with this code. The sprite supposed to move at the to the left when it reaches the right end corner. but this code does when it (sprite) reaches the right end corner, the sprite just stops.

The startM is the left end corner, and the endM is the right end corner

 //in constructor
 position = new Vector2(ShootingTreys.WIDTH*0.48f, ShootingTreys.HEIGHT*0.025f);

  // in update
 delta = Gdx.graphics.getDeltaTime();
 if(ps.touch == false){

        if(leftEnd == false && (startM <= ballMeter.getX()) ){
            position.x = ballMeter.getX();
            position.x += 20 *delta;

            if(endM == ballMeter.getX()){
                leftEnd =true;
            }
        }
        else {
            position.x = ballMeter.getX();
            position.x -= 20 *delta;

            if(startM == ballMeter.getX()){
                leftEnd = false;
            }
        }

        ballMeter.setPosition(position.x , ballMeter.getY() );

Solution

  • Make small change in your code.

    if(endM == ballMeter.getX()){
           leftEnd =true;
    }
    

    Convert to

    if(endM <= ballMeter.getX()){
           leftEnd =true;
    }
    

    And

    if(startM == ballMeter.getX()){
       leftEnd = false;
    }
    

    to

    if(startM >= ballMeter.getX()){
           leftEnd = false;
    }