# How can I rotate a Texture2D into / out of the screen?

I am drawing a Texture2D onto the screen and have the need to rotate the texture forward, in a 3D way. I'm using the SpriteBatch Draw() method and it only allows limited 2D rotation around the Z axis. From tons of research online I have boiled down the solution to passing either an effect or matrix to SpriteBatch's Begin() method; however, after many hours of trial and error I haven't come up with anything working.

• SpriteBatch doesn't allow that kind of behaviour, could you post some code of how you tried doing it with your own effect? – r2d2rigo Aug 14 '11 at 11:33
• @r2d2rigo SpriteBatch does allow it. You just need to give it the right settings. Using an appropriate Effect or Matrix, as Dave C suggested in the question, is a good start. – Andrew Russell Aug 15 '11 at 3:40

I sort of got it. Maybe with some tweaking you can get it the rest of the way.

first in the Update, I get the amount to rotate by

var ks = Keyboard.GetState();

if (ks.IsKeyDown(Keys.Down))
xAxis += 1f;
if (ks.IsKeyDown(Keys.Up))
xAxis -= 1f;



then create an effect and apply the transformation. The Matrix.CreateOrthographicOffCenter is just to position our camera. It is assuming a 800x600 screen. We then multiply it by our rotation transform.

BasicEffect e = new BasicEffect(GraphicsDevice);
e.World = Matrix.Identity;
e.View = Matrix.Identity;
e.TextureEnabled = true;
e.Texture = sprite;
e.Projection = Matrix.CreateOrthographicOffCenter(0, 800, 600, 0, 0, 1) * Xtransform;


Now in Draw just apply the effect to the SpriteBatch.Begin method (using the 4th overload). I say it sort of works because it only rotates TOWARDS the screen. It disappears when you rotate away. The picture below shows what it looks like before (top) and after (bottom). This is what you wanted, right? I know it just looks squished, but it is a 2d texture. It isn't meant to bend that way :)

• After I went to bed, I realized why it won't rotate backward. There is no texture back there! If you want to rotate the other direction you will need to do tell it to draw a different texture based on the angle you are at. So once you get past 90*, hide this texture, and start drawing another one. Maybe even filp it upside down for a better effect. – Joe Aug 26 '11 at 15:37