3x3 Matrix Rotation in C++

user2368229 picture user2368229 · May 21, 2013 · Viewed 14k times · Source

Alright, first off, I know similar questions are all over the web, I have looked at more than I'd care to count, I've been trying to figure it out for almost 3 weeks now (not constantly, just on and off, hoping for a spark of insight).

In the end, what I want to get, is a function where you pass in how much you want to rotate by (currently I'm working in Radian's, but I can go Degrees or Radians) and it returns the rotation matrix, preserving any translations I had.

I understand the formula to rotate on the "Z" axis in a 2D cartesian plane, is:

[cos(radians)    -sin(radians)    0]
[sin(radians)     cos(radians)    0]
[0                0               1]

I do understand Matrix Maths (Addition, Subtraction, Multiplication and Determinant/Inverse) fairly well, but what I'm not understanding, is how to, step-by-step, make a matrix I can use for rotation, preserving any translation (and whatever else, like scale) that it has.

From what I've gathered from other examples, is to multiply my current Matrix (whatever that may be, let's just use an Identity Matrix for now), by a Matrix like this:

[cos(radians) - sin(radians)]
[sin(radians) + cos(radians)]
[1]

But then my original Matrix would end up as a 3x1 Matrix instead of a 3x3, wouldn't it? I'm not sure what I'm missing, but something just doesn't seem right to me. I'm not necessarily looking for code for someone to write for me, just to understand how to do this properly and then I can write it myself. (not to say I won't look at other's code :) )

(Not sure if it matters to anybody, but just in-case, using Windows 7 64-bit, Visual Studio 2010 Ultimate, and I believe OpenGL, this is for Uni)

While we're at it, can someone double check this for me? Just to make sure it seems right.

A translation Matrix (again, let's use Identity) is something like this:

[1, 0, X translation element]
[0, 1, Y translation element]
[0, 0, 1]

Answer

Andrew picture Andrew · May 21, 2013

First, You can not have translation 3x3 matrix for 3D space. You have to use homogeneous 4x4 matrices.

After that create a separate matrix for each transformation (translation, rotation, scale) and multiply them to get the final transformation matrix (multiplying 4x4 matrix will give you 4x4 matrix)