Home > front end >  Basic idea of Quaternion y axis 90 degree rotate
Basic idea of Quaternion y axis 90 degree rotate

Time:09-17

I want to rotate the object around y axis 90 degree.

What I want to do is very simple

    getPosition(Quaternion rotation)
        rotation.y = rotation.y   90.0f;
        _rotateTarget.rotation = rotation;

it shows error.

I googled around and found I need to understand Quaternion

However I can't find first clue to rotate object simply 90 degree.

Is there any help??

CodePudding user response:

A Quaternion has not three but rather four components x, y, z and w! And they all move in the range -1 to 1.

=> Never touch the individual components of a Quaternion except you really know exactly what you are doing!


For rotating the object on the global Y-axis you rather want to use e.g. Quaternion.Euler as the name suggests generates a Quaternion rotation from the given Euler space angles.

Returns a rotation that rotates z degrees around the z axis, x degrees around the x axis, and y degrees around the y axis; applied in that order.

rotation *= Quaternion.Euler(0, 90, 0);
// Or also
//rotation *= Quaternion.Euler(Vector3.up * 90);
_rotateTarget.rotation = rotation;

Or if you want to rotate in any given axis you can also use Quaternion.AngleAxis

rotation *= Quaternion.AngleAxis(90, Vector3.up);
_rotateTarget.rotation = rotation;

And then you always combine two Quaternion using the multiplication * operator.

var final = rotA * rotB;

basically means first apply the rotation rotA then starting from there additionally apply the rotB.

rotation *= rotB;

is just a shorthand for writing

rotation = rotation * rotB;

CodePudding user response:

If you want to rotate an object smoothly to a target rotation you can use Quaternion.Slerp. The following script lets you set the x, y and z rotation.

[Header("Settings")]
public Vector3 targetRotation;
public float rotationSpeed = 5;

private Quaternion currentTargetRotation;

// Start is called before the first frame update
void Update()
{
    if (currentTargetRotation.eulerAngles != targetRotation)
        currentTargetRotation.eulerAngles = targetRotation;

    transform.rotation = Quaternion.Slerp(transform.rotation, currentTargetRotation, rotationSpeed * Time.deltaTime);
}
  • Related