Skip to content

SpriteBatch

In the Saxion Game App, we use a SpriteBatch from LibGDX to draw textures (images) on the screen. A texture can be anything from a character, a background, or an icon. The SpriteBatch helps us draw textures efficiently and supports transformations like scaling, rotation, and flipping.

Why we need the SpriteBatch

The SpriteBatch talks to the computer’s graphics hardware (GPU) to draw images. Drawing textures one by one can be slow, especially for games with many images on the screen. The SpriteBatch groups all the draw commands together and sends them to the GPU in one go, making rendering much faster.

How it works

Drawing textures consists of three phases:

1. Start the SpriteBatch

GameApp.startSpriteRendering();

This will create an vertex buffer in memory where we can draw on.

2. Draw the textures

Use methods like:

GameApp.drawTexture("player", 50, 50);
GameApp.drawTextureCentered("enemy", 300, 150);

You can specify position, size, rotation, and even flip textures horizontally or vertically. This will draw all of you textures in the vertex buffer.

3. End drawing

GameApp.endSpriteRendering();

This tells the computer, “I’m done drawing textures for now,” and the vertex buffer is sent to the GPU.

SpriteBatch

Figure 1. Overview of how the SpriteBatch works

Why start and end are important

You must always call startSpriteRendering() before drawing and endSpriteRendering() after drawing:

  • If you forget startSpriteRendering(), textures cannot be drawn, since there is no buffer.
  • If you forget endSpriteRendering(), textures will not show, since the buffer is never sent to the GPU.

Think of it like setting up a stage: you open the stage (start), place all your props (draw textures), then close the stage (end) to show the scene on the screen.