Open In App

Introduction To Phaser.js

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Phaser.js is a fast, free, and open-source JavaScript framework used for creating games for desktop and mobile platforms. It provides an extensive library of functions that enable developers to build games with rich graphics, physics, sound, and animations

What is Phaser.js?

Phaser.js is a popular HTML5 game framework that allows developers to create engaging 2D games using JavaScript or TypeScript. It provides built-in support for physics engines, animations, audio, and asset management, making it a comprehensive solution for game development.

  • Cross-platform compatibility: Games can be run on any device.
  • WebGL and Canvas rendering: For high performance phaser automatically selects the optimal rendering method for the device.

How Phaser.js Works?

Phaser games are designed using a game configuration object that defines properties such as dimensions, rendering type, physics settings, and scenes. Each scene has three main lifecycle methods

  • preload(): Loads assets like images and sounds.
  • create(): Initializes objects and game logic.
  • update(): Runs continuously to handle game logic and user interactions.

A basic Phaser game might look like this:

const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: { gravity: { y: 300 }, debug: false }
},
scene: { preload: preload, create: create, update: update }
};
const game = new Phaser.Game(config);

function preload() { this.load.image('sky', 'assets/sky.png'); }
function create() { this.add.image(400, 300, 'sky'); }
function update() { }

Let's Now Create a Basic Game using Phaser.js

Step 1: Create a project folder and files for the game.

mkdir phaser-games

Step 2: Install the phaser using npm in your project or use CDN in your HTML file.

Using npm

npm install phaser

Using CDN

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>

Image Resources

Apple: https://media.geeksforgeeks.org/wp-content/uploads/20241116122145948343/apple.png
Player: https://media.geeksforgeeks.org/wp-content/uploads/20241116122114324662/player.png
HTML
<!-- index.html -->
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Catch the Falling Object Game</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>
</head>

<body>
    <script src="main.js"></script>
</body>

</html>
JavaScript
//main.js

const config = {
    type: Phaser.AUTO,
    width: 400,
    height: 400,
    physics: {
        default: "arcade",
        arcade: { gravity: { y: 0 } },
    },
    scene: {
        preload: preload,
        create: create,
        update: update,
    },
};

const game = new Phaser.Game(config);
let player;
let cursors;
let fallingObject;
let score = 0;
let scoreText;

function preload() {
    this.load.image("player", "player.png");
    this.load.image("object", "apple.png");
}

function create() {
    // Add player with  dimensions
    player = this.physics.add.sprite(200, 350, "player");
    player.setDisplaySize(30, 30);
    player.setCollideWorldBounds(true);

    // Add falling object with dimensions
    fallingObject = this.physics.add.sprite(
        Phaser.Math.Between(25, 375),
        0,
        "object"
    );
    fallingObject.setDisplaySize(20, 20);
    fallingObject.setVelocityY(150);

    // Add collision detection
    this.physics.add.collider(player, fallingObject, catchObject, null, this);

    // Add score text
    scoreText = this.add.text(16, 16, "Score: 0", {
        fontSize: "20px",
        fill: "#fff",
    });

    // Input handling
    cursors = this.input.keyboard.createCursorKeys();
}

function update() {
    // Player movement
    if (cursors.left.isDown) {
        player.setVelocityX(-200);
    } else if (cursors.right.isDown) {
        player.setVelocityX(200);
    } else {
        player.setVelocityX(0);
    }

    // Reset falling object if it goes out of bounds
    if (fallingObject.y > 400) {
        resetFallingObject();
    }
}

function catchObject(player, object) {
    // Increase score and reset object
    score += 10;
    scoreText.setText("Score: " + score);
    resetFallingObject();
}

function resetFallingObject() {
    fallingObject.y = 0;
    fallingObject.x = Phaser.Math.Between(25, 375);
}

Output

In this example

  • preload() function: Loads the images for the player and the falling object (apple) into the game.
  • create() function:
    • Adds a player sprite at a specified position with adjustable size and enables collision with the game boundaries.
    • Creates a falling object sprite with adjustable size and sets its downward velocity.
    • Adds collision detection between the player and the falling object to trigger the score update.
    • Sets up text to display the current score and handles keyboard input for player movement.
  • update() function:
    • Monitors and updates player movement based on keyboard input (left and right arrow keys).
    • Resets the position of the falling object if it moves out of the game area.
  • catchObject() function: Handles the event when the player catches the falling object by increasing the score and resetting the object's position.
  • resetFallingObject() function: Resets the position of the falling object to a random x-coordinate at the top of the game window.ns of Phaser.js

Key Features of Phaser.js

Phaser offers a wide range of features that make game development very easy and smooth

  • Rich Physics Systems: Phaser supports multiple physics engines like Arcade Physics, Matter.js, and ImpactJS, which provide developers with tools for collision detection, gravity, acceleration, and more.
  • Scene and State Management: Phaser offers scene and state management, making it simple to create menus, game levels, and transitions.
  • Asset Loading: Phaser makes asset management easy through built-in asset loaders for images, audio, videos, sprite sheets, tilemaps, and more.
  • Animation: Creating animations in Phaser becomes very easy with built-in support for sprite sheets and frame-based animations.
  • User Input Handling: Phaser supports a variety of input methods, including keyboard, mouse, touch, and even game controllers.
  • Audio Management: Phaser provides built-in support for audio playback, including sound effects, music, and audio loops.
  • Camera and Viewport Control: Phaser's camera system let you control the visible area of a game, providing scrolling, zooming, and rotation functionalities.
  • Tilemaps: With support for tilemap-based levels, you can create vast game worlds and structured levels quickly.
  • Built-In Game Objects: Phaser provides built-in objects like sprites, text objects, buttons, graphics, and shapes. This reduces the need to create game components from scratch.

Applications of Phaser.js

Phaser.js has a wide range of applications, including

  • Casual Web Games: Phaser is ideal for creating browser games due to lightweight and its browser compatibility.
  • Educational Games: The framework is often used to develop educational games for children due to its simplicity and interactive capabilities.
  • Mobile Game Development: With mobile-friendly features, it's easy to develop cross-platform mobile games with touch and accelerometer support.
  • Prototypes and MVPs: Developers often use Phaser to build prototypes and minimum viable products (MVPs) quickly.
  • Game Jams: Due to its fast development cycle, Phaser is a popular choice for game jams and rapid prototyping events.

Comparison with Other Game Engines

  • Phaser vs. Cocos2d-x: Cocos2d-x supports both 2D and 3D game development and is cross-platform compatible. However, Phaser’s focus on HTML5 makes it highly suitable for rapid iteration.
  • Phaser vs. Unity 2D: Unity offers powerful tools for both 2D and 3D game development, providing an extensive editor and platform support. Phaser, on the other hand, is more lightweight, with easy to learn, making it ideal for developers focused on web games.
  • Phaser vs. Three.js: While Three.js used in creating animated 3D graphics in web browsers, Phaser focuses on 2D game development, making it better for browser-based games with rich 2D content.

Next Article

Similar Reads