I am trying to create a method that smoothly rotates an NPC so that they are facing the player or any other object. I looked on the internet and tried all the usual methods, but they either instantly rotate the NPC to about half of the desired rotation or completely freeze Unity! Is this a bug or am I doing something wrong?
My code is displayed below. Two of my failed attempts at smooth rotation are commented out.
/*bool rotating = false;
GameObject rotateTarget = null;*/
//Failed Attempt #1 (Part 1)
/*private void FixedUpdate()
{
while (rotating)
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(rotateTarget.transform.position - transform.position), 5);
if(Physics.Raycast(transform.position, transform.forward, 7.25f))
{
rotating = false;
}
}
}*/
public void TalkTo(string name)
{
ToggleWander();
//Failed Attempt #1 (Part 2):
/*rotateTarget = GameObject.Find(name);
rotating = true;
while (rotating)
{
}*/
//Failed Attempt #2:
/*while(!Physics.Raycast(transform.position, transform.forward, 7.25f))
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(GameObject.Find(name).transform.position - transform.position), 30 * Time.deltaTime);
Wait(0.5f);
}
*/
transform.LookAt(GameObject.Find(name).transform.position);
Debug.LogFormat("NPC is facing {0}: {1}", name, Physics.Raycast(transform.position, transform.forward, 7.25f));
Debug.LogFormat("Now talking to {0}", name);
ToggleWander();
}