Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate a 4x4 matrix (C#/XNA)

I've got an array of [4,4]
X is the only one I "know", the rest is calculated with a simple double for-loop.

x 0 0 0
0 0 1 0
0 1 1 0
0 1 0 0

I want a function that take this array, and rotate it 90 degrees + / - while the position of x stays the same. (It's supposed to be tetris)

x 0 0 0
1 1 0 0
0 1 1 0
0 0 0 0

I know some way to hardcode the permutations but what that wouldn't learn me anything and it's frankly quite boring.

Would appreciate the help :>

like image 903
user2072115 Avatar asked Feb 14 '13 13:02

user2072115


People also ask

What is a 4x4 rotation matrix?

The 4 by 4 transformation matrix uses homogeneous coordinates, which allow to distinguish between points and vectors. Vectors have a direction and magnitude whereas points are positions specified by 3 coordinates with respect to the origin and three base vectors i, j and k that are stored in the first three columns.

How do you rotate a matrix 270 degrees?

In the same way, you can rotate a matrix by 270 degrees by reversing the rows and then transposing. Lastly, you can rotate a matrix by 180 degrees by reversing the rows and the columns.

How do you rotate a matrix element?

The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.

How do you rotate a matrix function?

To perform the rotation on a plane point with standard coordinates v = (x, y), it should be written as a column vector, and multiplied by the matrix R: If x and y are the endpoint coordinates of a vector, where x is cosine and y is sine, then the above equations become the trigonometric summation angle formulae.


1 Answers

I'm not sure how exactly you intend to rotate a matrix by 90 degrees and yet still have the top left X in the top left of the rotated version, but to rotate something by 90 degrees, I'd just make a new array, swap rows and columns and flip horisontally.

int[][] start = new int[4][];
start[0] = new int[4] { x, 0, 0, 0 }
start[1] = new int[4] { 0, 0, 1, 0 }
start[2] = new int[4] { 0, 1, 1, 0 }
start[3] = new int[4] { 0, 1, 0, 0 }

int[][] rotate = new int[4][];
for (int i=0; i<4; i++) rotate[i] = new int[4];
for (int i=0; i<4; i++)
    for (int j=0; j<4; j++)
        rotate[i][j] = start[j][i];

Rotate finishes with:

0, 0, 0, 0,
0, 0, 1, 1,
0, 1, 1, 0,
0, 0, 0, 0,

Now this is a diagonal flip (EDIT: It just occurs to me that this will keep x in the same position: perhaps this is what you mean?), but just do a horisontal flip and it should be fine:

for (int i=0; i<4; i++)
    for (int j=0; j<4; j++)
        rotate[i][3-j] = start[j][i];

Rotate finishes with:

0, 0, 0, 0,
1, 1, 0, 0,
0, 1, 1, 0,
0, 0, 0, 0,

(To tilt other way: rotate[i][j] = start[j][3-i];)

:)

like image 88
AStupidNoob Avatar answered Sep 30 '22 13:09

AStupidNoob