Tinting sprites using a shader

Five slime sprites with different coloured tints

This tutorial will show you how to tint the pixels of a sprite in a shader. A sprite is a 2D texture / image.

The slime sprite flashes white every time the mouse is clicked. This could be used to show when an enemy has been hit in a video game.

Slime flash using tint shader
Slime flash using tint shader

GLSL shader code

#version 330 core

uniform sampler2D textureUnit;

// RGB
uniform vec3 tint = vec3(1.0f);

// Range from 0.0f to 1.0f
uniform float mixValue = 1.0f;

in vec2 texCoord;

out vec4 fragColour;

void main()
{
fragColour = texture(textureUnit, texCoord);
fragColour.rgb = mix(fragColour.rgb, tint, mixValue);
}

The tint shader is relatively simple and only requires 2 uniform values to be set.

The tint uniform is a vec3, which represents the RGB components. The colour channels are in the range of 0 to 1. The sprite will be tinted with this colour.

uniform vec3 tint = vec3(1.0f);

The mixValue uniform is a float in the 0 to 1 range. It represents how much of one colour you want to show.

  • 0 will show the original sprite.
  • 0.5 will show half of the original sprite, mixed with half of the tint.
  • 1 will show the full tint.
uniform float mixValue = 1.0f;

We first get the texture colour.

fragColour = texture(textureUnit, texCoord);

Then we simply mix the texture colour with the tint colour. Where mixValue determines which colour will be the most dominant.

fragColour.rgb = mix(fragColour.rgb, tint, mixValue);
tinting 5 slimes
Tinting 5 slimes

Thank you for reading this tutorial, I hope you found it useful!

Leave a comment