1
votes

I have issue with movement. My goal is to make player move once key is pressed for its own width/height. For example:

if (Gdx.input.isKeyJustPressed(Input.Keys.A)) 
    player.position.x = player.position.x-moveSpeed;

that works precise, but I want it more smooth, to move exact distance in a second, but each millisecond a bit, not all at once.

This makes player move smooth, but it's not precise:

if (Gdx.input.isKeyJustPressed(Input.Keys.A)) 
    player.position.x = player.position.x-moveSpeed*deltaTime;

How can I make smooth transition, but precise?

1
Have a look at easing tween functions like: gizma.com/easing The linear tweening may be what you want. There are also other tweening functions but all with the same input values (variables) - Andreas

1 Answers

0
votes

Change (or extend) your player class, so that it contains the following:

class Player {
    public final Vector2 position = new Vector2(); // you already have this
    public final Vector2 target = new Vector2();
    private final float speed = 10f; // adjust this to your needs
    private final static Vector2 tmp = new Vector2(); 
    public void update(final float deltaTime) {
        tmp.set(target).sub(position);
        if (!tmp.isZero()) {
            position.add(tmp.limit(speed*deltaTime));
        }
    }
    //The remainder of your Player class
}

Then in your render method you call:

if (Gdx.input.isKeyJustPressed(Input.Keys.A)) {
    player.target.x -= moveSpeed; //consider renaming moveSpeed to moveDistance
}
player.update(deltaTime);