Home > Blockchain >  Unity - rotated objects flips in a strange way when using Quaternions
Unity - rotated objects flips in a strange way when using Quaternions

Time:06-27

I'm trying to create a system in VR in which an object rotation follows the rotation of the player's hand. Unfortunately, when the hand rotates at a high angle, the rotated object flips in a strange way as if it had a problem with the rotation change from 360 degrees to 0. I tried many ways to solve this problem, but each one that worked did not allow me to change "sensitivity" on the basis of:

  • 1 - target is rotating 1: 1 ratio with hand
  • 2 - target is rotating twice as much as hand

etc.

// In FixedUpdate
Quaternion deltaRotation = Quaternion.Inverse(target.rotation) * hand.rotation;
deltaRotation.ToAngleAxis(out float angle, out Vector3 axis);
target.rotation *= Quaternion.AngleAxis(angle * sensitivity, axis);

Any help would be appreciated!

CodePudding user response:

So the problem is in

Quaternion deltaRotation = Quaternion.Inverse(target.rotation) * hand.rotation;

if the sensitivity is != 1 these objects rotations get desynchronized so the deltaRotation will not give you the value you expect. You probably wanted to check how much hand rotated since last frame, like that:

Quaternion _lastFrameRotation;

void Awake()
{
    _lastFrameRotation = transform.rotation;
}

private void FixedUpdate()
{
    Quaternion deltaRotation = Quaternion.Inverse(_lastFrameRotation) * transform.rotation;
    deltaRotation.ToAngleAxis( out float angle, out Vector3 axis );
    target.rotation *= Quaternion.AngleAxis( angle * sensitivity, axis );

    _lastFrameRotation = transform.rotation;
}
  • Related