Sprite Batch Flag Shader Tutorial

In October 2019, a fellow MonoGame Community member was asking if there was a shader that could render a sprite like a flag, or if someone could help with one they were writing. I had done something similar many moons ago with XNA, I however did this with a vertex stream (mesh) as opposed to a sprite batch (still a mesh really, but MG and XNA try to make it easier for us by having a SpriteBatch class)

So, how did I solve this?

Well, it's all in the shader really, lets look at the draw call in the Community11895 project.

As you can see, I am using an Effect, passing it a time value, and then just letting MG draw the textures.

So, whats in the shader that does all the magic?

It's all done in the pixel shader, in order to make the texture wave like a flag, we offset the texture uv value using a wave function over time, we do this in the function CalcUVAnimation.

So, with this we can now make our texture move like a waving flag, BUT, we also would like the texture to be "lit" as a flag would be, and in order to do that, we need to now calculate the amount of light hitting each pixel on the flags surface. If we dont do this, we still get a flag effect, but it's a bit bland like this.

So, in order to do that and apply some lighting to the texture, we need to know the normal of the texture. I do this by getting 3 corners, and then using those to get the tangent and bi normal of the pixel we can take the cross prouct of that and get the normal.

We can now calculate the diffuse term with that normal and light our pixel accordingly.

And we get our lovely lit flags.

If you want to check out the original post on the MG community forum, it's here. I think the OP was having issues with it on OpenGL, not sure why, if you have issues with OpenGL and this sample, please let me know.

The samples GIT Repo can be located here.

Become a patron to

12
Unlock 12 exclusive posts
Be part of the community
Connect via private message