Need help with Quaternions, please - Make a model spin while looking to a direction.

Ok, the documentation tells me I should try to not understand Quaternions and just use the methods Unity give me.

I tried it, I am still really very lost.

I’m trying to make an enemy look at the player and while, it keeps “looking” at the direction of the player, tts whole body is spinning on his axis

I can make a model keep “looking” at the other. I did it with Quaternion.Euler, with Quaternion.FromToRotation and with Quaternion.LookRotation.

But make it look at the player and keeping the body spinning like that… I just can’t. Whatever I try the rotation just goes crazy to different directions…

Anyone has any idea of the math behind that? Thank you a lot in advance.

Ok, again, found the solution myself using the LookAt method and then applying the rotation I want, instead of trying to do both things using Quaternion methods.

It looks something like this:

  public Transform target2;
  public float rotationSpeed = 45f;

void SpinBody()
{
     transform.LookAt(player.transform.position,Vector3.forward);
     Quaternion currentRotation = transform.rotation;
     rotationAmount += rotationSpeed * Time.deltaTime;
     Quaternion spinRotation = Quaternion.Euler(0f, 0f,  rotationAmount);
     Quaternion newRotation = currentRotation * spinRotation;
     transform.rotation = newRotation;
}

Of course you need to adapt to your solution if you trying to copy this code, and “player” is a Serialized GameObject field that points to the player.

Definitely kudos for working out quaternion rotations and combining them via multiplication. It’s something a lot of new users struggle with.

One suggestion is to use Quaternion.AngleAxis as opposed to a euler rotation around a specific axis, which produces a rotation upon the axis of the direction supplied. So should it need to look at any direction other than Vector3.forward, it can still rotate around the direction it points at.

1 Like