sameer karjatkar
sameer karjatkar

Reputation: 2067

Rotation implementation errors

I am trying to implement a rotation for a camera with the following function

mat3 rotate(const float degrees, const vec3& axis) {

    mat3 matrix=mat3(cos(degrees),0.0f,-sin(degrees),
        0.0f,1.0f,0.0f,
        sin(degrees),0.0f,cos(degrees)
        );
    mat4 m4=mat4(matrix)  ;
    return (m4 * vec4(axis,1));
}

However I am not able to convert mat4 to mat3. Also the multiplication of mat4 and vec3 is giving compilation errors

Upvotes: 0

Views: 199

Answers (2)

UnTraDe
UnTraDe

Reputation: 3867

There are rules for matrix multiplication, specifically: For AB the number of columns in matrix A must be equal to the number of rows in matrix B. Multiplying a matrix by a vector is valid because vector is like a one dimensional matrix, however, it must follow the above rule so multiplying a mat4 (a 4 by 4 matrix) by vec3 (a 3x1 matrix) is impossible because the number of columns is not equal to the number of rows, what you can do is create a vec4 (4x1 matrix) and fill the last component with 1, thus allowing you to multiply it with a mat4 matrix. You can read more about matrix multiplications here.

Another thing, like @David Saxon said, you have function returning mat3 while your return statement looks like this return (m4 * vec4(axis,1));, which will result in a vec4 (4x1 matrix), which is probably the reason you're getting this compilation error.

If you only want rotate a vector you don't have to use a 4x4 matrix, you can just multiply the mat3 by the vec3 you want to rotate, which will result in a vec3 representing the rotated vector.

Upvotes: 1

David Saxon
David Saxon

Reputation: 1436

In the return statement you're multiplying a 4x4 matrix by a 4 dimensional vector.

return (m4 * vec4(axis,1));

This returns a vec4, yet your function states it returns a mat3.

But I really think you need to review what you're trying to do. A camera uses a 4x4 matrix to define it's view matrix and glm already supplies convenience functions for rotating matrices.

glm::mat4 viewMatrix( 1.0f );
viewMatrix *= glm::rotate( angle, axis );

Upvotes: 3

Related Questions