Lightweight Pixel Perfect Outline

This is an optimized and simple outline shader designed for pixel perfect art at low resolution. Make sure you leave at least 1 transparent pixel border in your sprites.

It also includes code for making the sprite blink a certain color. You can set the blink_time_scale parameter to 0 to ignore this.

Shader code
shader_type canvas_item;
uniform vec4 outline_color : source_color = vec4(1.0);
//Blinking modulates the base color.
//Set blink_time_scale to 0 if you don't want blinking.
uniform vec4 blink_color : source_color = vec4(1.0);
uniform float blink_time_scale : hint_range(0.0, 10.0, 0.1) = 0.0;

void fragment() {
	vec2 pixel_size = TEXTURE_PIXEL_SIZE;
	bool within = texture(TEXTURE, UV + pixel_size * vec2(1.0, 0.0)).a > 0.0;
	within = within || texture(TEXTURE, UV + pixel_size * vec2(1.0, 1.0)).a > 0.0;
	within = within || texture(TEXTURE, UV + pixel_size * vec2(1.0, -1.0)).a > 0.0;
	within = within || texture(TEXTURE, UV + pixel_size * vec2(0.0, -1.0)).a > 0.0;
	within = within || texture(TEXTURE, UV + pixel_size * vec2(0.0, 1.0)).a > 0.0;
	within = within || texture(TEXTURE, UV + pixel_size * vec2(-1.0, 1.0)).a > 0.0;
	within = within || texture(TEXTURE, UV + pixel_size * vec2(-1.0, -1.0)).a > 0.0;
	within = within || texture(TEXTURE, UV + pixel_size * vec2(-1.0, 0.0)).a > 0.0;
	bool outline = within && texture(TEXTURE, UV).a == 0.0;
	COLOR = mix(COLOR, COLOR * blink_color, 0.5 - 0.5 * cos(TIME * blink_time_scale));
	COLOR = float(!outline) * COLOR + float(outline) * outline_color;
}
Tags
outline, pixel perfect, pixel-art
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from flytrap

2D Sonar

2d Nebula Shader

2D Procedural Water

Related shaders

Clean pixel perfect outline via material

Pixel Perfect outline Shader

Lightweight CRT Effect

guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Andrew M
Andrew M
2 months ago

Perfect and exactly what I needed. Thank you!