Game Physics - Rotation

A continuation of my self-driven attempt to learn a bit about 2D game physics, specifically vector rotation



Developing hobby games I usually just stick to libraries that already handle things like physics. Basically I follow examples, copy/paste code, and plugin numbers. This is good for getting a hobby game built but not so good to learn the math and gain an intuition of what’s actually going on, which is what I want to do now.

part 0 part 1 part 2.

Vector rotation is simple in principle! But really digging in and getting to understand the math made may head…. spin. hehe.

Anyhow, I did discover some things, but hit a wall with the intuition. I think I could get past this wall, but I would need to invest more time and effort than I really want to into understanding the math to a absurdly completionist point (and who knows, maybe I only think I understand it now!). To that end, I’d like to talk about what I do think I understand.

This article was written as I attempt to learn the subject matter at hand, so there is a strong possibility of incorrect information based on my own ignorance.

Please, if you see an error of any kind, feel free to send me an email!


The simple case is to consider what happens when you rotate a unit vector in 90 degree increments. Specifically, let’s consider the vector [1, 0]. The sequence of values will be: [1, 0], [0, 1], [-1, 0], [0, -1]

From this, a pattern emerges:

x’ = -y y’ = x

This breaks down for any other increment than 90, but that’s because 90 is a special case for a more generalized formula (where t is an angle):

x’ = cos(t)x - sin(t)y y’ = sin(t)x + cos(t)y

This is more often represented in matrix form (called a rotation matrix):

R(t) = |cos(t) -sin(t)| |sin(t) cos(t)|

But when it’s multiplied by a vector [x, y] you’ll get the first formula. Even with all of the reading and exploration that I’ve done, I don’t think I fully grok this enough to really explain it without regurgitating text book information that doesn’t really explain everything. My current understanding is that the formula is basically deriving an x/y offset caused by the first angle, then figuring out the second angle in x/y, then applying the offset.

Yay! Time for some code, which is a lot more concise that the above :)

proc rotate*(self: Vector, angle: float): Vector =
    var cs = cos(angle), s = sin(angle)
    result.x = cs*self.x - s*y
    result.y = s*self.x + cs*self.y

# a special case, slightly faster than the general formula
proc rotate90*(self: Vector): Vector =
    result.x = -self.y
    result.y = self.x


I’ve briefly explained what needs to be done to calculate the rotation of a vector, and I think I’ve learned a bit along the way – though not enough to truly grok the operation.

Next week will likely not be a continuation of this series, but a diversion into the 31st Ludum Dare 48-hour game competition, which I am competing in this weekend!