Wednesday, April 22, 2009

Quickie Rotations

In my C# codebase I have no rotation code - which may be a little surprising but as I'm making a 2D game it's not been a issue until now.

I just want to be able to rotate my sprites around other sprites. A nice general solution would be to allow matrices to be be applied to the four vertices that make up each corner of my sprite.

But I didn't want to write a matrix class. So I just implemented the rotation manually:

public void Rotate(double angle, EinPoint origin)
for (int i = 0; i < _rawVerts.Count(); i++)
float cosAngle = (float)Math.Cos(angle);
float sinAngle = (float)Math.Sin(angle);
float newX = (_rawVerts[i].x - origin.x) * cosAngle + (_rawVerts[i].y - origin.y) * sinAngle;
float newY = (_rawVerts[i].y - origin.y) * cosAngle - (_rawVerts[i].x - origin.x) * sinAngle;
_rawVerts[i].x = newX + origin.x;
_rawVerts[i].y = newY + origin.y;

I'll be the first to say it's not pretty and there's probably a way to avoid the casting. But for my needs it's perfect. I've promised myself I'll implement all the matrix code once I finished my current game - which is coming along quite nicely.

Here's a good rotation reference.

I'm using OpenGL so of course I could use the OpenGL rotation commands - push a matrix, do the rotation, pop the matrix. But doing it this way sends extra commands to the graphics card. If I do the translation manually them I can skip those commands and I only need to pay for the cost of doing the rotation once instead of every frame. I'm thinking of also doing some rotations in my particle system so it's worth considering these issues.
Post a Comment