emandret
emandret

Reputation: 1399

Quaternions and translations

I created a small program that can rotate a 3D object in space.

To sum it up quickly, I created a function to perform matrix rotations using quaternions:

void        matrix_rotate(float matrix[][4], float angle, t_vec4 rotation_axis)
{
    float   rotate[4][4];
    t_vec4  quat;

    quat = quaternion_create(angle, rotation_axis); // Create a quaternion from an axis-angle representation
    quaternion_to_matrix(rotate, quat);             // Convert the quaternion to a rotation matrix
    matrix_multiply(matrix, rotate);                // Multiply the rotation matrix
}

So I can for instance perform a 90-degrees rotation on the y-axis to the model matrix (the t_vec4 is a 4D vector, composed of 4 floats x, y, z, w):

matrix_rotate(model, 90.0, (t_vec4){0.0, 1.0, 0.0, 0.0});

It works so far. But the rotation is related to my world origin (0, 0, 0). I would like to translate the rotation axis of my quaternion.

How can I translate the rotation axis of a quaternion to rotate an object around its own axis and not the world origin ?

Upvotes: 1

Views: 1489

Answers (2)

Michael Kenzel
Michael Kenzel

Reputation: 15951

First of all, there is really no need to use quaternions here. If all you want is create a matrix that rotates around a given axis by a given angle, then you can just do that. You're effectively already doing it anyways, just via the detour of using a quaternion in the middle…

Quaternions can only represent rotations. One could use dual quaternions to work with rotations and translations in a unified manner. However, that would seem to be massive overkill here. To get a matrix that rotates around an axis that passes through a point that is not the origin, you can just first translate the coordinate system such that the point you want your rotation axis to go through becomes the origin. Then you apply the rotation. And then you translate everything back. So if p is the vector of coordinates of the point you want the rotation axis to go through, you first translate everything by -p, then you rotate, and then you translate back by p

Upvotes: 1

Zefick
Zefick

Reputation: 2119

The easiest way to achieve what you want is the first rotate an object in world's origin and then move it in the desired position. So just swap rotation and position matrices.

Upvotes: 1

Related Questions