Sprite Outline with Phaser 3
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.
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.
- Sprite Outline (Animated!) 2D Shader Graph Tutorial
- Writing Shaders In Unity 2D Sprite Outline
- WebGL Image Processing
- 2D Sprite Outline Shaders
- Why shaders are cool and how to use them in Phaser 3
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.
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!