Phaser: GameObjects

By

Learn how to add GameObjects in Phaser inside the create function, drawing shapes with this.add.circle and text with this.add.text and its options.

~~~

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

Everything you place in a Phaser scene is a GameObject: shapes, text, images, sprites. Inside the create function we can add GameObjects to the game using the this.add factory.

this in the context of the function refers to the scene object. The scene gives us this.add, an object with one method per GameObject type.

Drawing shapes

For example we can draw shapes, like a circle:

function create() {
  const circle = this.add.circle(100, 100, 90, 0xffffff)
}

This adds a white circle at position (100, 100), with a radius of 90. Those numbers are expressed in pixels.

The circle variable contains a reference to the newly added circle. Keep that reference around if you plan to move or change the object later.

The fourth argument is the fill color, written as a hexadecimal number: 0xffffff is white, 0xff0000 is red.

We can add a rectangle in a similar way, passing width and height:

const rect = this.add.rectangle(300, 100, 120, 80, 0xff0000)

Adding text

Another example is this.add.text(), which adds text to the game:

const text = this.add.text(130, 100, 'test')

You can customize how text looks, by passing a set of options:

const text = this.add.text(50, 100, 'Test', {
  font: '20px Arial',
  fill: '#FFFFFF'
})

Notice the color format changed. Shapes want a hexadecimal number like 0xffffff, while text styles want a CSS color string like '#FFFFFF'. Mixing the two formats is a common mistake, and the color silently comes out wrong.

Working with properties

Any GameObject has a set of properties. For example we can access the x and y axis positions, in the 2D space, using text.x and text.y.

Those properties are writable. Assigning a new value moves the object:

text.x = 200

You can also set both at once:

text.setPosition(200, 150)

Changing properties over time is how you animate things, and we’ll do that in the update function later in the series.

Where is the origin point?

Be careful with positioning. Shapes are positioned by their center: our circle’s center sits at (100, 100). Text instead is positioned by its top-left corner.

So a circle and a text placed at the same coordinates won’t visually line up. If that surprises you, change the origin:

text.setOrigin(0.5)

This tells Phaser to treat the text’s center as its position, matching how shapes behave.

Tagged: Phaser · All topics
~~~

Related posts about phaser: