Question

I am writing a C# program that has a cube object that allows the user to move it in the x y and z axis. However i want them to be able to rotate it aswell.

My matrix is defined as so: public double[, ] matrix = new double[4, 4];

So for example i was able to scale the cube via this code.

public void initAsScalingMatrix(double sx, double sy, double sz) {

initAsIdentityMatrix();
matrix[0, 0] = sx; // scale x
matrix[1, 1] = sy; // scale y
matrix[2, 2] = sz; // scale z
matrix[3, 3] = 1;
}

So my question is. How could i use the same approach to rotate the cube around for example the x axis?

EDIT---

Hi,

I have figured out how to rotate it but it is doing it from way of in the top left corner.

matrix[0, 0] = Math.Cos(rz);
matrix[0, 1] = Math.Sin(rz);
matrix[1, 0] = -(Math.Sin(rz));
matrix[1, 1] = Math.Cos(rz);

How could it rotate from the center?

Was it helpful?

Solution

You need to multiply your rotation matrix by a translation matrix to get a matrix that will rotate your object around a non-origin position.

That's a bit of a mouthful so looking at it this way might help:

First apply a translation matrix to your cube that moves the center of the cube (or rotation origin) to the world origin (0,0). Now apply your rotation matrix. Now apply the opposite translation to put the cube back to it's original position. Of course now it will be rotated AND in it's original "position", which is what you want.

Effectively what's been done is applying a matrix (Trans x Rotation x ^Trans) to the cube.

Your rotation matrix is 2D. If you want to rotate around arbitrary 3D axes you need to use a 3D rotation matrix. If you install the XNA framework for C# you will get a matrix math library for free. XNA is supposed to be for games but depending on what you are doing you might find it useful to use for the matrix math rather than rolling your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top