2D Rim Light

This creates a rim light around the edges of a sprite, giving the appearance of a light source behind the sprite. Works best using a normal map. All light aside from the edges will be ignored. Without a normal map, the light will look like an outline around the sprite based on the light source.

Shader code
shader_type canvas_item;

uniform float radius = 50.0; // how far the rim light should go
uniform float intensity = 2.0; // how bright the rim light should be compared to the light source
uniform int accuracy: hint_range(4, 256) = 32; // set it higher for better appearance but worse performance, should be at least 4

const float PI = 3.14159;

void light() {
    vec4 light = texture(TEXTURE, UV);
    vec2 size = TEXTURE_PIXEL_SIZE * radius;
    float min_dist = max(size.x, size.y);
    float alpha = 0.0;
    bool pixel_found = false;
    // the goal is to find the nearest pixel where the alpha is 0, which should be the edge of the sprite
    // iterate through each circle size, starting with the smallest
    for(float current_radius = 0.0; current_radius < max(size.x, size.y); current_radius += min(TEXTURE_PIXEL_SIZE.x, TEXTURE_PIXEL_SIZE.y)){
        // check each angle of the circle
        for(float rad = 0.0; rad < 2.0 * PI; rad += (2.0 * PI) / float(accuracy)){
            float x = cos(rad) * current_radius;
            float y = sin(rad) * current_radius;
            alpha = texture(TEXTURE, UV + vec2(x, y)).a;
            // if the nearest pixel with alpha 0 is found, end the search
            if(alpha == 0.0){
                min_dist = min(min_dist, sqrt(x*x + y*y));
                pixel_found = true;
        if(pixel_found) break;

    float alpha_amount = clamp(1.0 - min_dist / min(size.x, size.y), 0.0, 1.0);
    LIGHT.a = light.a * intensity * alpha_amount;

2d, 2d light, light, sprite
The shader code and all code snippets in this post are under MIT license and can be used freely. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

2D Rim Light

2D Light Z-Depth

Modulate Before Light

Inline Feedbacks
View all comments