Physics is a core component of most games, allowing objects to move, collide, and interact in realistic or stylized ways. Phaser provides a powerful and easy-to-use physics system that you can enable on your game objects (sprites) to bring your games to life.

In this section, you will learn:

  • The basics of physics systems in Phaser
  • How to enable physics on sprites
  • How to configure physics properties (like velocity, gravity, and bounce)
  • Practical examples and exercises

  1. Physics Systems in Phaser

Phaser supports multiple physics engines. The most commonly used are:

Physics System Description Use Case Example
Arcade Simple, fast, and easy to use Platformers, shooters
Matter Advanced, supports complex shapes and joints Physics puzzles, simulations
Impact For compatibility with ImpactJS games Porting old ImpactJS games

For most 2D games, Arcade Physics is sufficient and is the default in Phaser.


  1. Enabling Arcade Physics on Sprites

Step-by-Step Guide

  1. Enable Physics in Game Configuration

    When creating your Phaser game, specify the physics system in the configuration:

    const config = {
      type: Phaser.AUTO,
      width: 800,
      height: 600,
      physics: {
        default: 'arcade',
        arcade: {
          gravity: { y: 300 }, // Applies gravity to all objects
          debug: true          // Shows physics bodies for debugging
        }
      },
      scene: {
        preload: preload,
        create: create,
        update: update
      }
    };
    
    const game = new Phaser.Game(config);
    

    Explanation:

    • default: 'arcade' sets Arcade Physics as the default system.
    • gravity: { y: 300 } applies downward gravity to all physics-enabled objects.
    • debug: true helps visualize physics bodies during development.
  2. Creating a Physics-Enabled Sprite

    In your scene's create method, add a sprite and enable physics:

    function create() {
      // Add a sprite at position (100, 450)
      player = this.physics.add.sprite(100, 450, 'player');
    
      // Set bounce and collision with world bounds
      player.setBounce(0.2);
      player.setCollideWorldBounds(true);
    }
    

    Explanation:

    • this.physics.add.sprite creates a sprite with physics enabled.
    • setBounce(0.2) makes the sprite bounce slightly when it lands.
    • setCollideWorldBounds(true) prevents the sprite from leaving the game area.

  1. Configuring Physics Properties

You can further control how your sprite behaves with various methods:

Method Description Example Usage
setVelocity(x, y) Sets the velocity in pixels/second player.setVelocity(100, 0)
setGravityY(value) Sets vertical gravity for this object player.setGravityY(500)
setBounce(value) Sets how bouncy the object is (0 = none, 1 = full) player.setBounce(1)
setCollideWorldBounds(bool) Prevents object from leaving the game area player.setCollideWorldBounds(true)

Example:

player.setVelocity(150, -300); // Moves right and up
player.setGravityY(600);       // Stronger gravity for this sprite
player.setBounce(0.5);         // Medium bounce

  1. Practical Example: Bouncing Ball

Let's create a simple scene where a ball falls, bounces, and stays within the game bounds.

function preload() {
  this.load.image('ball', 'assets/ball.png');
}

function create() {
  // Add a ball sprite with physics
  ball = this.physics.add.sprite(400, 100, 'ball');

  // Set bounce and world bounds
  ball.setBounce(0.8);
  ball.setCollideWorldBounds(true);

  // Optional: Set initial velocity
  ball.setVelocity(100, 200);
}

Explanation:

  • The ball will fall due to gravity, bounce when it hits the bottom, and not leave the screen.

  1. Exercise: Make a Jumping Player

Task:
Create a player sprite that starts at the bottom of the screen. When the spacebar is pressed, the player should jump (move upward).

Starter Code

function preload() {
  this.load.image('player', 'assets/player.png');
}

function create() {
  player = this.physics.add.sprite(400, 550, 'player');
  player.setCollideWorldBounds(true);
  player.setBounce(0.2);

  cursors = this.input.keyboard.createCursorKeys();
}

function update() {
  if (cursors.space.isDown && player.body.touching.down) {
    player.setVelocityY(-400); // Jump up
  }
}

Solution Explanation:

  • player.body.touching.down checks if the player is on the ground (prevents double jumps).
  • setVelocityY(-400) gives the player an upward velocity, making it jump.

Common Mistakes & Tips

  • Forgetting to enable physics: If you use this.add.sprite instead of this.physics.add.sprite, the sprite won't respond to physics.
  • Not setting world bounds: Without setCollideWorldBounds(true), sprites can leave the visible area.
  • Gravity confusion: Remember, positive Y gravity pulls objects down.

Summary

  • Phaser's Arcade Physics system is simple and efficient for most 2D games.
  • Enable physics by using this.physics.add.sprite and configuring properties like bounce, velocity, and gravity.
  • Always set setCollideWorldBounds(true) to keep objects within the game area.
  • Use keyboard input and velocity to create interactive movement, like jumping.

Next Steps:
In the next section, you'll learn how to detect and handle collisions and overlaps between physics-enabled objects, allowing for more interactive and dynamic gameplay!

© Copyright 2024. All rights reserved