- Home /
Turning character slowly with Slerp
I make my character walk using a navmesh and when he arrived I would like him to turn towards the character he is in front of. I use the following function but I keep getting errors and I can't get it to work.
public static IEnumerator TurnToFaceSmoothly (Transform targetThatWalks, Transform targetToLookAt) {
while (Vector3.Dot (targetThatWalks.forward, (targetToLookAt.position - targetThatWalks.position).normalized) < 0.95f) {
Vector3 dir = targetToLookAt.position - targetThatWalks.position;
targetThatWalks.rotation = Quaternion.Slerp(targetThatWalks.rotation, Quaternion.LookRotation(dir), 5f * Time.smoothDeltaTime);
targetThatWalks.eulerAngles = new Vector3(0f, targetThatWalks.eulerAngles.y, 0f);
yield return null;
}
I call this function as following in my "static IEnumerator doWalkingAction()" method:
yield return StartCoroutine (TurnToFaceSmoothly (playerObj.transform, npcObj.transform));
Which gives me the following error: [QUOTE]error CS0120: An object reference is required to access non-static member `UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)'[/QUOTE]
I tried removing the static and calling the function just with:
TurnToFaceSmoothly (playerObj.transform, npcObj.transform);
However when I did this I noticed that the function never ever gets called, I put some debug.log's in that turntofacesmoothly function and they never showed up (and obviously the turning did not happen as well)
What am i doing wrong? I cannot seem to figure it out, i've been stuck here for hours and hours.
Answer by SkaredCreations · Dec 29, 2014 at 12:53 PM
You're using coroutines statically but in your doWalkingAction you're using playerObj which I think is (reading the exception message) a local member of the script. As the message states: you cannot use the class members directly in the static functions because they belongs to an instanced object. Your second try (calling directly the function without StartCoroutine) is wrong because if you call that way it's not creating a "coroutine loop" (which is part of StartCoroutine) and instead it's called just once.
@SkaredCreations Thank you for your answer.
I found a script StaticCoroutine (static coroutine). This is I guess what I need, but how do I use this? I noticed when I tried implementing it that it calls the function non-stop ins$$anonymous$$d of just once?
It depends on where/when you call the coroutine, but I still don't understand why you're doing in a static function ins$$anonymous$$d of doing this in a script attached to the navmesh agent.
Your answer
Follow this Question
Related Questions
Lerp not working 1 Answer
How to use Vector3.Lerp without slow-down 3 Answers
Smoothly Rotate Object Towards Target Object 1 Answer
Lerp takes me to 0,0,0 2 Answers
Changing object location every 3 second 2 Answers