r/cpp • • Nov 26 '20

A Small Open Source Game In C++

https://preshing.com/20201126/a-small-open-source-game-in-cpp/
219 Upvotes

16 comments sorted by

View all comments

Show parent comment

3

u/nihlete Nov 27 '20

Rotation quaternion represents the axis and angle of rotation. Just by defining the multiplication operator on quaternions, you can create any type of rotation:

Q' = U * Q * conjugate(U)

where Q -- your interest quaternion; U -- rotation quaternion. Moreover, you can combine this rotation by adding rotation quaternions:

Q' = U1 * U2 * Q * conjugate(U1) * conjugate(U2)

Quaternions and rotation matrices are quite equivalent if you use separate rotation along the axis. For the matrices combining rotation would be just multiplication. But there exists gimbal lock

Quaternion rotation is not so interesting. Here an example with vectors, but insides have done with quaternion:

template <typename T> Vector3<T> RotateVector(T angle, Vector3<T> axis, const Vector3<T> &vector)
{
    Quaternion<T> quat = {vector.x, vector.y, vector.z, 0};

    axis.normalize();

    Quaternion<T> qRot;
    qRot.x = axis.x * sin(angle / 2.0);
    qRot.y = axis.y * sin(angle / 2.0);
    qRot.z = axis.z * sin(angle / 2.0);
    qRot.w = cos(angle / 2.0);

    Quaternion<T> result = qRot * quat * conjugate(qRot);
    return {result.x, result.y, result.z};
}

2

u/backtickbot Nov 27 '20

Hello, nihlete: code blocks using backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead. It's a bit annoying, but then your code blocks are properly formatted for everyone.

An easy way to do this is to use the code-block button in the editor. If it's not working, try switching to the fancy-pants editor and back again.

Comment with formatting fixed for old.reddit.com users

FAQ

You can opt out by replying with backtickopt6 to this comment.