Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 36 ยท Getting Started

Your First Phaser Game: Setup, Scene and Click Target

Build your first complete Phaser game: the HTML page, loading Phaser from a CDN, a scene class, a score, a timer and a click target. Runs live in the browser.

In the last lesson you ran a ready-made example. Now you will build a complete game from an empty file. It is small, a target that jumps around the screen while you click it for points, but it has everything a real game has: a page, a game configuration, a scene, objects, input, a score and a timer.

The smallest web page for a Phaser game

All you need is an HTML file with a place for the canvas and a script tag for Phaser. Save this as index.html and open it in a browser; you do not need a web server for this simple version, because Phaser is loaded from a CDN (a public file host).

HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My first Phaser game</title>
  <style>
    body { margin: 0; background: #0b1120; display: grid; place-items: center; min-height: 100vh; }
  </style>
</head>
<body>
  <div id="game"></div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script>
  <script src="game.js"></script>
</body>
</html>

Three things matter here:

  • the <div id="game"> is the parent element where Phaser will insert its <canvas>;
  • the Phaser script must come before your own script, because your code uses the Phaser global;
  • your game code can live in a separate file (game.js) or inline. In this track the examples are inline so each one is self-contained.

Pin the version. [email protected] in the URL fixes the exact version. If you wrote phaser@latest, your game could change behavior when a new release appears. Pin the version and upgrade on purpose.

Planning the game

Before coding, decide what the game is. Here it is in four lines:

  1. A round target appears on the screen.
  2. When the player clicks it, the score goes up by one and the target jumps somewhere else.
  3. A timer counts down from 15 seconds.
  4. When time runs out the game stops and shows the final score.

Each line maps to a Phaser feature: game objects, input events, a text object and a timer event. That mapping from game rules to Phaser features is the real skill in this course.

flowchart LR
  A["create()"] --> B["add target + texts"]
  B --> C["target.on('pointerdown')"]
  C --> D["score++ and move target"]
  B --> E["time.addEvent every 1 s"]
  E --> F["timeLeft-- ; at 0 stop"]

Two event streams drive the game: clicks and a one-second timer.

The complete game

Click the target

Click the red circle. Let us look at the new ideas, one at a time.

Properties on this

Inside a scene, this is the scene object. We store the score and timer on it (this.score, this.timeLeft) so every method can read and update them. This is the normal way to share state between create, update and your own helper methods. We reset them at the top of create, which matters later when a scene restarts: a restarted scene should start clean.

Text objects

this.add.text(x, y, 'text', style) creates a text object. To change what it shows, call setText. Creating a new text object every time the score changes would pile up objects and waste memory, so we create the text once and update it. setOrigin(1, 0) anchors the right edge of the timer to the screen edge.

Shapes and interactivity

this.add.circle(x, y, radius, color) is a shape game object. Shapes are handy for prototypes because they need no image files. setInteractive() tells Phaser to watch this object for pointer input. Without it, the circle is only a drawing. Once interactive, it emits events such as pointerdown, pointerup, pointerover and pointerout. The useHandCursor option shows the hand cursor on hover.

Timer events

this.time is the scene's clock. this.time.addEvent({ delay: 1000, repeat: 14, callback, callbackScope }) runs callback after one second and then repeats 14 more times, so 15 calls in total. The callbackScope makes this inside tick refer to the scene. An arrow function keeps the same this automatically:

JavaScript
this.time.addEvent({ delay: 1000, repeat: 14, callback: () => this.tick() });

Scene timers are paused when the scene is paused and destroyed when the scene shuts down, which is exactly what you want in a game. That is why you should prefer this.time over plain setTimeout.

Random numbers

Phaser.Math.Between(min, max) returns a random integer between the two values, inclusive. Phaser has its own random number generator (Phaser.Math.RND) that can be given a seed, which makes random games reproducible for testing.

Ending the game properly

endGame sets a flag (this.playing = false), disables the target's input, fades it with setAlpha(0.2) and adds the result text. The guard if (!this.playing) return; in the click handler is a safety net. A game is full of these small state checks: "is the round active?", "is the player alive?". Whenever you add a feature, ask which states it should work in.

To restart the game after "Time up", you could call this.scene.restart(). Because create resets score and timeLeft, everything starts fresh. You will learn scene control in Multiple Scenes.

Improving it: a pop animation

A small visual reward makes clicks feel good. Phaser's tween system (more in Tweens and Timelines) can animate any numeric property. Here the target shrinks and grows back each time it is hit, and the game uses a seeded random generator so each run places the target in the same order.

Click the target with a pop effect

The seed option in the config feeds Phaser's random generator. With the same seed, Phaser.Math.Between returns the same sequence every run, which makes bugs easier to reproduce.

Troubleshooting a blank page

If your game shows nothing:

  1. Open the console. A red error tells you the file and line.
  2. Phaser is not defined means the Phaser script tag is missing, misspelled or placed after your script.
  3. A black canvas often means create never ran: check that your scene is in the scene option of the config.
  4. Loading images from a file:// page fails, because browsers block those requests for security. Use a local web server as soon as you load images or sound (Phaser with Vite and npm shows one).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must the Phaser script tag come before your own game script?

    Scripts run in order. new Phaser.Game and class X extends Phaser.Scene need the Phaser global to exist already.
  2. 2. What must you call on a shape before it can emit pointerdown events?

    Game objects ignore input until you call setInteractive, which registers them with the input system.
  3. 3. Why is this.time.addEvent usually better than setTimeout in a scene?

    Scene timers follow the scene lifecycle, so you do not get callbacks firing after the scene has ended.
  4. 4. A text object shows the score. What is the right way to update it?

    Create the text once in create() and update it with setText; creating new objects every time wastes memory.

Summary

  • A Phaser page needs a parent element, the pinned Phaser script and your game code, in that order.
  • A scene class with a create method is the starting point; keep game state in properties on this.
  • Shapes, text and setInteractive() are enough to build a complete small game.
  • this.time.addEvent creates scene-bound timers; Phaser.Math.Between makes random numbers; a seed makes them repeatable.
  • Add state flags such as playing so events do the right thing at the right time.

Next: The Game Configuration Explained