Timers and delayed events are essential tools in game development, allowing you to schedule actions, create countdowns, spawn enemies at intervals, and manage time-based gameplay mechanics. Phaser provides robust support for timers and delayed events through its built-in time management system.
Key Concepts
- Timer: A mechanism to execute code after a certain amount of time or at regular intervals.
- Delayed Event: An action scheduled to occur after a specified delay.
- Repeating Event: An action that occurs repeatedly at set intervals.
- Scene Time: Phaser manages timers within the context of a scene, ensuring they are paused or stopped when the scene changes.
Phaser’s Time System
Phaser uses the this.time
object within a scene to manage timers and events. The most common methods are:
Method | Description |
---|---|
this.time.addEvent |
Adds a single or repeating timed event |
this.time.delayedCall |
Schedules a one-time callback after a delay |
this.time.removeEvent |
Removes a previously created timed event |
Practical Examples
- Scheduling a One-Time Event
Suppose you want to display a message 2 seconds after the game starts.
// Inside your Phaser Scene this.time.delayedCall(2000, () => { this.add.text(100, 100, '2 seconds passed!', { fontSize: '24px', fill: '#fff' }); });
Explanation:
2000
is the delay in milliseconds (2 seconds).- The callback function adds text to the scene after the delay.
- Creating a Repeating Timer
Let’s spawn an enemy every 1.5 seconds.
this.time.addEvent({ delay: 1500, // 1.5 seconds callback: spawnEnemy, callbackScope: this, loop: true }); function spawnEnemy() { // Example: Add a sprite at a random position this.add.sprite(Phaser.Math.Between(50, 750), 100, 'enemy'); }
Explanation:
delay
: Time between each event (in ms).callback
: Function to call each time.callbackScope
: The context (this
) for the callback.loop: true
: Makes the event repeat indefinitely.
- Countdown Timer Example
Display a countdown from 5 to 0.
let countdown = 5; let countdownText = this.add.text(400, 300, countdown, { fontSize: '48px', fill: '#fff' }).setOrigin(0.5); this.time.addEvent({ delay: 1000, // 1 second callback: () => { countdown--; countdownText.setText(countdown); if (countdown === 0) { countdownText.setText('Go!'); } }, repeat: 5 // Runs 6 times (from 5 to 0) });
Explanation:
- The event runs every second, updating the displayed number.
- When the countdown reaches 0, it displays "Go!".
Table: Timer Event Options
Option | Type | Description |
---|---|---|
delay |
Number | Time in ms before the event triggers |
callback |
Function | Function to call when the event triggers |
callbackScope |
Object | Context for the callback function |
loop |
Boolean | Whether the event repeats indefinitely |
repeat |
Number | Number of times to repeat (0 = once, 1 = twice, etc) |
startAt |
Number | Start the timer at a specific elapsed time (ms) |
timeScale |
Number | Speed multiplier for the timer (1 = normal speed) |
Practical Exercises
Exercise 1: Flashing Text
Task:
Create a text that appears and disappears every 0.5 seconds.
Hint:
Use a repeating timer and toggle the text’s visibility.
Solution
let flashText = this.add.text(400, 200, 'Flashing!', { fontSize: '32px', fill: '#ff0' }).setOrigin(0.5); this.time.addEvent({ delay: 500, callback: () => { flashText.visible = !flashText.visible; }, loop: true });
Tip:
A common mistake is forgetting to set loop: true
, which would make the text flash only once.
Exercise 2: Delayed Game Over
Task:
Show "Game Over" 3 seconds after a player’s health reaches zero.
Hint:
Use this.time.delayedCall
inside your health check logic.
Solution
if (playerHealth <= 0) { this.time.delayedCall(3000, () => { this.add.text(400, 300, 'Game Over', { fontSize: '48px', fill: '#f00' }).setOrigin(0.5); }); }
Tip:
Make sure not to trigger multiple delayed calls if the health check runs repeatedly.
Common Mistakes and Tips
- Forgetting to set
loop: true
: Without this, your timer will only run once. - Not using
callbackScope
: If you use a regular function (not an arrow function),this
may not refer to your scene. - Timers and Scene Changes: Timers are tied to the scene. If you switch scenes, timers in the previous scene are destroyed.
- Overlapping Timers: Be careful not to create multiple timers for the same purpose, which can lead to unexpected behavior.
Summary
- Phaser’s time system allows you to schedule one-time or repeating events easily.
- Use
this.time.delayedCall
for single delayed actions andthis.time.addEvent
for repeating or more complex timers. - Timers are essential for creating dynamic, time-based gameplay elements like countdowns, enemy spawns, and UI effects.
- Always manage your timers carefully, especially when switching scenes or repeating events.
Next:
You’re now ready to explore more advanced gameplay features, such as AI and enemy behavior, which often rely on timers and delayed events for dynamic interactions!
Phaser - Game Development with JavaScript
Module 1: Introduction to Game Development and Phaser
- What is Game Development?
- Overview of Phaser
- Setting Up Your Development Environment
- Your First Phaser Project
Module 2: Phaser Basics
- Understanding the Game Loop
- Game Configuration and Scenes
- Loading and Displaying Images
- Working with Text
- Handling Input (Keyboard and Mouse)
Module 3: Sprites and Animation
Module 4: Game Physics and Interactivity
- Introduction to Physics in Phaser
- Enabling Physics on Sprites
- Collisions and Overlaps
- Interactive Objects and Events