libgdx

Moving actors on path with constant speed

Simple movement between two locations

For this the best solution is using actions. To add a new action to an actors in Scene2D just call:

Action action = Actions.moveTo(x,y,duration);
actorObject.addAction(action);

Where x and y is the target location and duration is the speed of this movement in seconds(float).

If you want to stop this action(and the actor by it) you can do it by calling:

actorObject.removeAction(action);

or you can remove all actions by calling:

actorObject.clearActions();

This will immediately stop the running of the action(s).

The moveTo action manipulates the x and y property of the actor, so when you draw the actor to the screen always use getX() and getY() to draw textures. Just like in the following example:

public class MovingActor extends Actor {

    private Action runningAction;
    private float speed = 2f;

    public void moveTo(Vector2 location) {
       runningAction = Actions.moveTo(location.x, location.y, speed);
       this.addAction(runningAction);
    }

    public void stopAction() {
       this.removeAction(runningAction);
    }

    public void stopAllActions() {
       this.clearActions();
    }

    @Override
    public void draw(Batch batch, float parentAlpha){
        batch.draw(someTexture, getX(), getY());
    }
}

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow