toji/gl-matrix

[QUESTION] How to rotate a matrix back to 0?

axelthat opened this issue · 4 comments

Suppose I have a following rotated matrix which is rotated to 45 degrees,

const matrix = new Float32Array([
    0.7071067690849304, 0.7071067690849304, 0, 0, 
    -0.7071067690849304, 0.7071067690849304, 0, 0, 
    0, 0, 1, 0, 
    150, 150, 0, 1
])

Now I want to rotate this matrix back to 0 degrees,

import { mat4 } from "gl-matrix"

const OUT = new Float32Array([
    0, 0, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
]);

const matrix = new Float32Array([
    0.7071067690849304, 0.7071067690849304, 0, 0, 
    -0.7071067690849304, 0.7071067690849304, 0, 0, 
    0, 0, 1, 0, 
    150, 150, 0, 1
])

const res = mat4.rotateZ(OUT, matrix, 0)
console.log(res)

However the result is still,

new Float32Array([
    0.7071067690849304, 0.7071067690849304, 0, 0, 
    -0.7071067690849304, 0.7071067690849304, 0, 0, 
    0, 0, 1, 0, 
    150, 150, 0, 1
])

What am I doing wrong here?

Thank you for including code, makes it much easier to reproduce this.
So, the issue is that you're rotating the matrix by zero radians, you'll want to do something like this

mat4.rotateZ(OUT, matrix, Math.PI/4);

(You can also use the helper function for converting degrees to radians )

@stefnotch Thanks for the reply. But I want to rotate the matrix back to 0 not to Math.PI / 4.

@sanjade

The glmatrix rotation functions rotate matrices. They do not set the rotation of a matrix.

For example, the following would rotate a matrix by Pi/2 radians (90 degrees) twice. Or, in total, rotate the matrix by Pi radians (180 degres)

mat4.rotateZ(matrix, matrix, Math.PI/2);
mat4.rotateZ(matrix, matrix, Math.PI/2);

On that note, I did miss a sign.

res = mat4.rotateZ(mat4.create(), matrix, -Math.PI/4)
// Output: Float32Array(16) [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, … ]

mat4.str(res)
// Output: "mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 150, 150, 0, 1)"

And finally, depending on your mathematical background, this might be helpful
image

Oh okay. So that's how it works. Thanks a lot.