When working on my 2D lighting system, I needed to create some shadows. Shadows for sprites can easily be created by skewing the sprite and drawing it in all black. How much you skew depends on the position in relation to the light source. I already had a lighting and shadow system working in XNA, and now I just needed to get it working in Unity.

My first thought was to perfrom a skew from within Unity, in C#, like I did in XNA. As it turns out, you can’t (you can skew GUI elements, but not actual game objects). If you want to skew game objects, you need to skew the mesh itself, which I did actually get to work. However, this solution was a little ugly, and I’m not sure about the performance ramifications when recalculating every frame. So, I set off to find a more elegant solution.

My next idea was to try to skew the sprite from within the vertex shader. I knew it had to be possible, but I wasn’t sure exactly how. To my great surprise (and frustration), I was absolutely unable to find a simple vertex shader skew demo or tutorial anywhere on the web. I searched for literally hours one day, but came up empty. I suppose I shouldn’t be too surprised, since vertex shaders are rarely used with pure 2D games.

With no options left, I had a go at it myself. After a bit of trial and error I was able to create a working solution. All in all, it actually took less time for me to implement it myself than I spent searching for a tutorial! Sigh. Live and learn.

I’ll share the shader here in hopes of saving someone the hassle of what I went through. For a great article on understanding skew matrices themselves, check out this Flash transformation matrix tutorial. Enjoy!