- Home /
Quaternion.Slerp with Quaternion.LookRotation causes unexpected results
I'm using Quaternion.Slerp to rotate a GameObject, so it looks at a target, which is a Vector3, but the GameObject rotates different then expected, it looks right up in the "sky", for instance, when it should look at the center of the area (which is not above it).
My code:
public IEnumerator TurnToTarget(Vector3 target, float rotDuration) { // the hunter is turning turning = true; // play the animation //animation.Play("Rotate"); print ("playanim:Rotate"); // the starting rotation Quaternion startRotation = transform.rotation; // the rotation needed to face the target Quaternion newRotation = Quaternion.LookRotation(target.normalized, Vector3.up); /*Vector3 newRotEuler = newRotation.eulerAngles; newRotEuler = new Vector3(newRotEuler.x,transform.rotation.eulerAngles.normalized.y,newRotEuler.z); newRotation = Quaternion.Euler(newRotEuler);*/
// test if the rotation is equal
if(startRotation == newRotation)
{
// then the hunter has no reason to turn, so he doesn't
turning = false;
// exit the coroutine
yield break;
}
// set the elapsed time var to 0
float elapsedTime = 0.0f;
// turning loop
while (elapsedTime < rotDuration)
{
// add time elapsed since last frame to elapsed time var
elapsedTime += Time.deltaTime;
float t = elapsedTime / rotDuration;
// Slerp to the target
transform.rotation = Quaternion.Slerp(startRotation,newRotation,t);
// return here next frame
yield return null;
}
// when done, turning is false
turning = false;
//transform.LookAt(target);
}</code></pre>
Answer by whydoidoit · Mar 15, 2013 at 11:58 AM
LookRotation takes a direction not a position (unlike LookAt)
So you need
var rotation = Quaternion.LookRotation(target - transform.position, Vector3.up);
Thanks, that works perfectly. Now I'll just feel bad for not reading the script reference properly.
Your answer
Follow this Question
Related Questions
i want to get my to cube to rotate 90 degrees on the x-axis as it jumps 0 Answers
Rotating about and only one axis 1 Answer
Quaternion Rotation Smooth 1 Answer
LookRotation Between 2 Points 1 Answer
few question about quaternion slerp 3 Answers