Timers (basics)
In LibGDX, your game updates every frame in the render(float delta) method. You can implement timers in this method by keeping track of elapsed time manually. We use the delta parameter for this. Since summing these values will give us the total run time of the application.
Basic Timer
public class MyGameScreen implements ScalableGameScreen {
private float elapsedTime = 0f; // stores elapsed time
private float spawnInterval = 2f; // 2 seconds
...
@Override
public void render(float delta) {
super.render(delta);
// Add the time passed since the last frame
elapsedTime += delta;
// Check if enough time has passed
if (elapsedTime >= spawnInterval) {
spawnEnemy(); // your action
elapsedTime = 0f; // reset timer
}
// ... other game update and drawing code
}
private void spawnEnemy() {
System.out.println("Enemy spawned!");
}
...
}
Explanation:
- delta is the time (in seconds) since the last frame. LibGDX automatically provides this.
- elapsedTime accumulates time.
- When elapsedTime reaches spawnInterval, the action happens, and the timer is reset.
Countdown Timer
You can also count downwards:
private float countdown = 5f; // 5 seconds
@Override
public void render(float delta) {
super.render(delta);
countdown -= delta;
if (countdown <= 0) {
System.out.println("Time's up!");
countdown = 5f; // reset countdown
}
}
Multiple Timers
The following example show how you can use multiple timers:
private float enemyTimer = 0f;
private float powerUpTimer = 0f;
@Override
public void render(float delta) {
super.render(delta);
enemyTimer += delta;
powerUpTimer += delta;
if (enemyTimer >= 3f) {
spawnEnemy();
enemyTimer = 0f;
}
if (powerUpTimer >= 10f) {
spawnPowerUp();
powerUpTimer = 0f;
}
}
Notes
- Always use delta from
render()— never assume a fixed frame rate. - Reset your timer after the action happens, otherwise it will repeat every frame.
- This method is frame-accurate and works for both simple and complex game logic.