/

Phaser: Physics

Phaser: Physics

This post is part of a Phaser series. Click here to see the first post of the series.

Phaser offers three different built-in physics engines: Arcade, Matter.js, and Impact (Impact.js compatible). In this post, we will focus on the Arcade physics engine.

To enable the Arcade physics engine, add a physics property to the Phaser.Game initialization config object:

1
2
3
4
5
6
7
8
9
const config = {
//...
physics: {
default: 'arcade',
arcade: {
debug: false
}
}
}

You can add physics to a single GameObject by using the this.physics.add.sprite() method:

1
const dog = this.physics.add.sprite(20, 20, 'dog')

Alternatively, you can create a physics group. Groups are useful for setting up common rules for multiple items. There are two types of groups: static groups and dynamic groups. Static groups contain static bodies, while dynamic groups contain dynamic bodies.

For example, to create a static group for platform objects:

1
2
3
4
5
6
7
//in preload()
this.load.image('ground', 'assets/platform.png')

//in create()
const platforms = this.physics.add.staticGroup()
const ground = this.add.sprite(200, 200, 'ground')
platforms.add(ground)

Note: You can download the asset from here.

To create a dynamic group, use the this.physics.add.group() method:

1
const dogs = this.physics.add.group()

Items can be added to a group using the items.add() method:

1
2
3
const dogs = this.physics.add.group()
const dog = this.add.sprite(20, 20, 'dog')
dogs.add(dog)

Groups also provide a convenient create() method that can be used to create GameObjects automatically:

1
2
3
4
5
platforms.create(200, 200, 'ground')

//instead of
const ground = this.add.sprite(200, 200, 'ground')
platforms.add(ground)

Once you have set up the physics objects, you can start working on collisions.

tags: [“Phaser”, “Physics”, “Game Development”]