Reputation: 75
The code below is from Unity's tutorial on Quaternions. If you copy/paste the code it makes your object orbit around the target. My question is: WHY? Why does it results on that? And why would I do it like that when I can just use transform.RotateAround()? Note that if you change the code SLIGHTLY it behaves completely differently. For instance, if I change the 3 to a -3, the object just runs away.
public Transform target;
void Update()
{
Vector3 relativePos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
Quaternion current = transform.localRotation;
transform.localRotation = Quaternion.Slerp(current, rotation, Time.deltaTime);
transform.Translate(0, 0, 3 * Time.deltaTime);
}
Upvotes: 2
Views: 963
Reputation: 176
First the givens.
relativePos
is the vector direction from to target.
LookRotation
is a function that derives a Quaternion
from a vector you'd like your object to face towards.
Slerp
Spherically interpolates rotation between two rotations meaning it rotates from a given rotation to another smoothly.
Now to the explanation.
It revolves around the target because of the transform.Translate
without it your object will just rotate to face the target (because of the LookRotation
) on its own axis with no movement. In the tranform.Translate
the third parameter (3 * Time.deltaTime) means move the object forward along its z axis 3 units/second therefore it revoles because it's constantly trying to move 3 units/second on the z axis but the Slerp
keeps pulling it in making it rotate towards the target so tranform.Translate
moves it and Slerp
keeps rotating it back to target which results in orbiting.
And you can't just use transform.RotateAround()
because
transform.LookAt()
but that'll result in some jittery effects while on the code above Slerp
Spherically interpolates rotation which basically means smoother rotation and less jittery.transform.Translate
The object runs away because in tranform.Translate
the third parameter (3 * Time.deltaTime) means move the object forward along its z axis 3 units/second while -3 means move it backward therefore it runs away But if you look closer it's still facing the target. Instead of moving back on the Z axis it moves back along the direction facing the target because of the LookRotation
and Slerp
functions.
I hope this explained it well if you have any more questions/need more clafication just reply and I'll get back to you.
Upvotes: 1