Skip to content

Moving a sprite across the screen

Thomas Cashman edited this page Sep 16, 2013 · 1 revision

Please read the Basic Concepts wiki page before following this tutorial.

Each update is considered a timestep in your engine, i.e. your engine should advance by the delta value. However, render is never called at a consistent rate. You might target 60 frames per second but in reality it will fluctuate between 59 and 61 frames per second. This means render may be called between your timesteps. So, to ensure your sprites move smoothly we must calculate the sprite render position during the interpolate method using the alpha variable. The alpha variable represents the percentage of a timestep that has occurred before render is to be called.

Let's look at an example of implementing a Player class.

Our player class will need to store the character's coordinates between timesteps, i.e. the current position and the previous position. This way we can calculate its render coordinate during the interpolate method. For this example, we'll make the player move 4 pixels each timestep.

public class Player {
     private Point previousPosition;
     private Point currentPosition;
     private Sprite sprite;

     public Player() {
          previousPosition = new Point();
          currentPosition = new Point();
          //Initialise sprite
     }

     public void update() {
          previousPosition = currentPosition.cpy();
          currentPosition.set(currentPosition.x + 4f, currentPosition.y + 4f);
     }

     public void interpolate(float alpha) {
          //Use the lerp (linear interpolate) method from LibGDX 
          //to interpolate between the previous and current positions
          //This will return the render coordinates
          Vector2 renderPosition = previousPosition.lerp(currentPosition, alpha);
          sprite.setPosition(renderPosition.x, renderPosition.y);
     }

     public void render(Graphics g) {
          g.drawSprite(sprite);
     }
}

Clone this wiki locally