# Math behind simulating a simple light source for rotated rectangle?

Say I have a 2D Rectangle. By offsetting its position by x y and rendering a shadow by an offset, it gives the illusion of a shadow. If I rotate the rectangle Z degrees and try it with the same offset, it appears as though the light source has moved. How can I compensate for the angle so it appears as though the shadow is always coming from the same direction?

-
@davidluzgouveia 45 degrees, 90 degrees, I already used X and Y so Z was the next variable. I do not mean Z axis rotation. – jmasterx Dec 9 '11 at 4:16
Could you perhaps add a little drawing of what you need? I tried recreating this but I'm not sure if the effect I'm seeing is wrong. It seems right to me... – David Gouveia Dec 9 '11 at 4:21

I tried recreating this and to me it seems like the light source is fixed correctly, e.g. here the light source remains to the top right of the figure:

So I think maybe what you're doing wrong is the order in which you apply the rotation and the offset. You need to apply the rotation first, and then the translation. (And if you had a scale, it would also need to come before the translation)

I'm using XNA so SpriteBatch already got the multiplication order right for me by default :) But here's my code for reference anyway:

``````private Vector2 position = new Vector2(450, 200);
private Vector2 offset = new Vector2(-100, 100);
private float rotation = 0f

spriteBatch.Begin();
spriteBatch.Draw(shadow, position + offset, null, Color.Black * 0.2f, rotation, origin, Vector2.One, SpriteEffects.None, 0f);
spriteBatch.Draw(shadow, position, null, Color.White, rotation, origin, Vector2.One, SpriteEffects.None, 0f);
spriteBatch.End();
``````

On this example I'm also rotating the rectangle around its center, but I tried with the origin set to zero and it didn't cause any problems for the shadow.

And to show you why order of multiplication matters when applying transformations check this image:

The reason for this behavior is simply because transformations are always applied using the "origin" of the current space. Translation remains the same regardless of the origin, since it's just a displacement and does not need a point of reference. But scaling and rotation vary greatly as you can see from the picture.

Applied to your example of shadows if you don't keep in mind the correct order you'll get a shadow that's glued to your figure!

-
Excellent answer, and with pictures! – mpnk121 Dec 10 '11 at 8:47