Sprite Outline with Phaser 3

Junhong Wang
2 min readJun 19, 2020

--

This is a series of posts that attempt to create more beginner friendly tutorials for phaser 3, inspired by Modular Game Worlds in Phaser 3.

Source: Dungeon tileset II by 0x72

There wasn’t a working solution/example online for implementing sprite outline with Phaser 3, so I’m here to provide one. By the end of this tutorial, you will have something like this:

Resources

This tutorial was made with the help of these resources.

Fragment Shader

Fragment shader is one of the rendering stages where it decides what colors to draw. By default, Phaser Sprite uses the fragment shader fromPhaser.Renderer.WebGL.Pipelines.TextureTintPipeline . We will need to modify this to make an outline. Here’s the source code of the shader we need to modify.

Original Fragment Shader

Here’s the idea: If you pay a close attention to the blue border below, you will notice that a pixel is part of the outline only if it is transparent and one of its neighboring pixels is not transparent.

Based on this logic, we can easily modify the shader code as follows:

Note the texture coordinates are from 0 to 1, so we can’t just increment/decrement by 1 to reach the adjacent pixel. The trick here is to pass the texture size as a uniform variable. Then the inverse of the texture size is the unit of 1 pixel.

Here’s the OutlinePipeline class that uses the fragment shader above.

Before you can use this pipeline, there are two things you need to do.

  • Since it is a custom pipeline, you need to register it when the game starts.
  • It requires an extra uniform uTextureSize to render

Registering the pipeline is as simple as one function call. In your scene, write

To set the uniform, write

in your sprite class.

Edit: You also need to tell the sprite that you want to use the outline pipeline.

That should be all you need!

--

--

Junhong Wang

I'm Junhong. I'm a Software Engineer based in LA. I specialize in full stack web development and writing readable code. junhong.wang