Skip to content

Moving a sprite across the screen

Thomas Cashman edited this page Sep 14, 2017 · 4 revisions

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. mini2Dx provides the CollisionPoint, CollisionCircle and CollisionBox classes to simplify this.

For this example, we'll make the player move 4 pixels each timestep.

public class Player {
     private CollisionPoint point;
     private Sprite sprite;

     public Player() {
          point = new CollisionPoint();
          sprite = new Sprite(new Texture(Gdx.files.internal("texture.png")));
     }

     public void update() {
          //preUpdate() must be called before any changes are made to the CollisionPoint
          point.preUpdate();
          //Move the point by 4 pixels on the X and Y axis
          point.set(point.getX() + 4f, point.getY() + 4f);
     }

     public void interpolate(float alpha) {
          //This method uses the lerp (linear interpolate) method from LibGDX 
          //to interpolate between the previous and current positions
          //and set the render coordinates correctly
          point.interpolate(null, alpha);
     }

     public void render(Graphics g) {
          //Use the point's render coordinates to draw the sprite
          g.drawSprite(sprite, point.getRenderX(), point.getRenderY());
     }
}

Clone this wiki locally