eliasg13
eliasg13

Reputation: 1

How to properly use Quaternions to deviate x amount from the original rotation?

I'm on my way to release my first game, and on the finishing touches got stuck with Quaternions.

I have a GameObject with my scrips, and a child of it contains the mesh. When The car drift, I'm trying to rotate the mesh x degrees from the resting position, and when the car acelerates or desacelerates, a bit on the x axe acording to it, but it just rotates randomly on the y direction. Any clue?

void RotateMesh()
{
    float xRotation = -90 - thrust * 20;
    float yRotation = -transform.rotation.eulerAngles.y;
    float zRotation = 0 - rightVelocity * 50;
    mesh.rotation = Quaternion.Euler(xRotation, yRotation, zRotation);
}

Upvotes: 0

Views: 209

Answers (1)

Martin Prazak
Martin Prazak

Reputation: 1605

According to the documentation, the Quaternion.Euler class "Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis.", suggesting that this implements the z-x-y euler angles.

Unfortunately, with Euler angles, the axes cannot be seen as independent - the operation would create a quaternion that rotates around the Z axis first, then takes the result and rotate that using the X rotation, and the result of that is then rotated around the Y axis. Unfortunately, Unity doesn't seem to implement any different type of Euler angles - if you need to change the order, you might want to experiment with something like:

mesh.rotation = Quaternion.Euler(0, yRotation, 0) * 
     Quaternion.Euler(xRotation, 0, 0) * Quaternion.Euler(0, 0, zRotation);

As I don't have the rest of your game, I can't test the precise order that works for your intended use case - the above is just an example of how to create a quaternion implementing a different euler angles type than the default.

Upvotes: 1

Related Questions