Hit flash
Push a sprite toward a flat color for a few frames when it takes damage, so the hit reads at a glance.
Cards
One live example to tweak, learn and copy.
How it works
When a character takes a hit, games often turn its sprite white (or red) for a few frames. It costs almost nothing and
tells the player instantly that the attack landed, even in a crowded screen. The shader part is small: read the
sprite, mixBlends from a to b by a factor t, along a straight line. GLSL calls it mix; HLSL and most node editors call it lerp. Linear interpolation (mix) Blends from a to b by a factor t, along a straight line. GLSL calls it mix; HLSL and most node editors call it lerp.mix(a, b, t) = a (1 − t) + b t
The timing lives in game code, not in the shader. The amount is a uniformA value the host code sets before a draw call that stays the same for every vertex and pixel of that draw, like the time, the canvas size or a color. Uniform A value the host code sets before a draw call that stays the same for every vertex and pixel of that draw, like the time, the canvas size or a color.
The sprite still draws with ordinary alpha blendingCombining the color a fragment shader outputs with the color already in the framebuffer, instead of replacing it. Transparency, additive glow and multiply all come from it. Blending Combining the color a fragment shader outputs with the color already in the framebuffer, instead of replacing it. Transparency, additive glow and multiply all come from it.result = src × srcFactor + dst × dstFactor: the flash changes its color, never its
coverage. The White flash card shows the basic version; a damage tint (a red flash that fades slower) and an
invincibility blink (toggling the flash on and off with time) use the same mix with a different color and amount.
Further reading
- Relative luminance (opens in a new tab)Reference
- Blend modes (opens in a new tab)Reference
- Alpha compositing (opens in a new tab)Reference
- mix (opens in a new tab)Reference
- clamp (opens in a new tab)Reference
- Linear interpolation (opens in a new tab)Reference
- texture (opens in a new tab)Reference
- texelFetch (opens in a new tab)Reference
- Using textures in WebGL (opens in a new tab)Docs
- Uniforms (opens in a new tab)Book
- Window: requestAnimationFrame() method (opens in a new tab)Docs
- The OpenGL ES Shading Language, version 3.00 (opens in a new tab)Docs
- Blending (opens in a new tab)Article
- WebGLRenderingContext: blendFunc() method (opens in a new tab)Docs
- Spatial shaders (opens in a new tab)Docs
- CanvasItem shaders (opens in a new tab)Docs
- Resource (opens in a new tab)Docs