Physics
We want to create the conditions for the character to exist in the world — this includes things like velocity, but also what happens when the character jumps and lands. Setting up the physics environment will also help us do more actions with this character and other characters that we could create, as well.
Step 1 — Initialize the Physics Interactions for the Hero and the Platforms in the Play.ts File
Using the add.collider method from the Phaser physics engine, we will add a constraint between objects in the game — the hero and the platforms within a level.
- A collider is a type of physics body that can interact with other physics bodies. When two “colliders” overlap on the screen, Phaser automatically calculates the physics response (i.e., bouncing, sliding, stopping, etc).
- Our method — initPhysics() — sets up these physics interactions between the hero character and the platform so that the character can “stand” on the platforms or interact with them in some way.
// Play.ts
export class Play extends Phaser.Scene {
//...
initPhysics() {
this.physics.add.collider(this.hero, this.level.platforms);
}
//...
}
- Using this. specifies that we only want this collider to function for the instance of hero and a level’s platforms in the current state.
Next, add a call to the initPhysics() method within the create() method.
- The create() method is called once when the game scene is first created or when a player enters a new level.
- On creation, we want to include the setup for the physics interactions that we just wrote.
// Play.ts
export class Play extends Phaser.Scene {
//...
create() {
console.log('Play.create()');
this.initLevel();
this.initPhysics();
}
//...
initPhysics() {
this.physics.add.collider(this.hero, this.level.platforms);
}
//...
}
Step 2 — Configure the Physics Settings
Make sure that your Config.ts file has the correct settings for the physics key:
// Config.ts
import Phaser from "phaser";
import { Boot } from './Boot';
import { Play } from './Play';
export const gameConfig = {
type: Phaser.AUTO,
width: 960,
height: 600,
roundPixels: true,
backgroundColor: 0x000000,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
// debug: true,
},
},
scene: [Boot, Play],
};
Checkpoint
- The character should start on top of the platform.
- The character should move left and right and be stopped by any objects in the way.