Godot Visual Shader: Flag

GodotEngine Feb 19, 2019

The Problem

I needed a simple animated flag material. It doesn't need to be a physic based. Just a simple "cartoon" like movement. It's easy to do and fast to calculate.

Making a simple shader with a sin-wave and gradient to control it. Flag needs to makes big moves at the end and stay still in the beginning where it's attached to the pole.

Video

If you prefer to look at the video and hear my voice instead of read this article I've made it possible. It's more or less the the same material just in more modern form.

VLOG version of the article

You can ignore this and just read.

Vertex

Vertex Shader overview

First the vertex  position is decomposed to X, Y and Z values.

Now the moving part.

Time is multiplied for faster move and added to the X value. This is the base for sinus function. Basically for each X position the wave is calculated and time moves this wave along (time is always increasing).

This wave would be way to big so ten it's multiplied by .2 to make it 80% smaller. This is only the offset it needs to be added to the original Y position. And that's what that last node is making.

Gradient

This would make the flag wave with the same amount on all length. Not what I wanted. Gradient fixes this. Dark values (0) represents no move and white full move. It's multiplied by 3 just to make it look right.

Mixing gradient with sinusoid

Lastly the gradient value is mixed with original Y value. The mixing (ScalarInterp) will take a (original Y value) or B (Y with the wave offset) based on the C (gradient). Now on the beginning it's original Y and no move and moving forward (X) it makes bigger waves. X and Z values are not changed. Final vertex is composed and pushed to the output vertex.

Fragment

This part is as simple as it can be. It just adding texture to the albedo.

Logo on the flag

My flag doesn't need more changes here as it's a simple logo. But for more realistic fabrics heres a place for all normal maps, roughness, etc.