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);
}
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
- You won't be able to configure which way your object faces it'll just revolve around a target. You can use it in combination with
transform.LookAt()
but that'll result in some jittery effects while on the code aboveSlerp
Spherically interpolates rotation which basically means smoother rotation and less jittery. - You won't be able to specify rotation radius with
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.
No comments:
Post a Comment