← Pixel Dreamer Studio

Hit flash shader for 2D sprites

A canvas_item shader that mixes in white, a tween to fade it, and one material per enemy.

Mix the sprite's color toward white in a canvas_item shader, keep the texture's alpha so only drawn pixels flash, and tween the flash amount from 1 to 0. Give every enemy its own material, or hitting one flashes them all.

Two round red sprites on a dark background, the left one flashing white
The script below in Godot 4.7: the left sprite mid-flash, the right one untouched.

The code

Put this script on your enemy's Sprite2D and call flash() from your damage code. It builds the shader itself, so there is no shader file to set up.

extends Sprite2D
## Hit flash: the sprite turns white, then fades back. Call flash() when it takes damage.

@export var flash_time := 0.15

const FLASH_SHADER := """
shader_type canvas_item;
uniform float flash : hint_range(0.0, 1.0) = 0.0;
uniform vec4 flash_color : source_color = vec4(1.0);

void fragment() {
	vec4 c = texture(TEXTURE, UV) * COLOR;
	COLOR = vec4(mix(c.rgb, flash_color.rgb, flash), c.a); // keep alpha: only drawn pixels flash
}
"""

var _tween: Tween

func _ready() -> void:
	if not material is ShaderMaterial:
		var mat := ShaderMaterial.new()
		mat.shader = Shader.new()
		mat.shader.code = FLASH_SHADER
		material = mat  # made here, so every sprite gets its own


func flash() -> void:
	if _tween:
		_tween.kill()  # a new hit restarts the flash
	_tween = create_tween()
	_tween.tween_method(_set_flash, 1.0, 0.0, flash_time)


func _set_flash(v: float) -> void:
	(material as ShaderMaterial).set_shader_parameter("flash", v)

In our test the hit sprite turned white and went back to its own color once the flash time was over. The transparent corners around it stayed transparent.

Every enemy flashes at once

That happens when the enemies share one ShaderMaterial, for example when it is set in the inspector of a scene you instance many times. We gave two sprites the same material and flashed one: both turned white.

Turn on Local to Scene for the material, under Resource in the inspector. With it on, each instance of the scene got its own copy and only the hit sprite flashed. The script above avoids the problem another way: it makes a new material in _ready() when none is set.

The whole rectangle turns white

A shorter shader, COLOR = mix(texture(TEXTURE, UV) * COLOR, vec4(1.0), flash);, mixes the alpha toward 1 as well. In our test it turned the transparent corners of the sprite white too, so the flash showed as a white square. Mix only the color and keep the alpha, as the shader above does.

What to change

Tested in Godot 4.7 with the Compatibility renderer.

Want ready-made effects? Try the free Arcane VFX pack or the VFX Collection for Godot 4.