How to Create A Phaser 3 Text Style Library

Create A Text Style Library in Phaser 3

When I’m writing a game, I’m really into the logic of it. If I have to stop and look up fonts and colors all the time, my brain has to shift focus. In any case, I don’t like to throw things away. I did something in Phaser 2, similar to the text style library I’m about to show you, for a project for my office. It got too complex for me to keep setting the fonts, colors, font sizes and origins (anchors) of the text fields over and again. Too many variations kept creeping in, so I came up with the TextUtil, which is basically a library of styles.

phaser 3 text style library

Set Up Style Names

The first step is to set up the class TextUtil and accept parent as the sole parameter. This will be the scene passed down into our class instance. Second, we set up some static variables to use to identify the styles.

Make the text field

This is where we create the text field itself. The getBasicText() function has two parameters:

  1. text-required-The text inside the text field.
  2. style-optional-One of the styles strings defined in the constructor.

If there is not a style passed in we can just create a text field without it. If there is, then the text options are looked up in the getStyle() function, which is not yet created. We will also set the origin to 0.5 to center the text field. Last we send the style key to the setStroke function to check if we need to apply a stroke. We will write this later.

Get the style config object

The getStyle function is mainly a case switch statement that assigns values to the textConfig object. If none is found, then no style gets placed on the textField.

Setting Strokes

The setStroke function also looks up the key on the switch statement and assigns a stoke to the textfield which we passed from the getBasicText() function

How to Use

I would love to get up a collection for the community to share. If you have an interesting text combination to share, please comment below!

Leave a Reply