I am trying to make wander code for my player and the part for it wandering and going around is working however the part that stops the wander and makes it go back into idle doesn’t work. I tested it and I know the if statement doesn’t trigger and I am unsure why. I know that the player gets close enough to the destination by making the chosen destination public. I have also tried using Mathf.Approximately
however that didn’t change anything.
Why might this happen? If there is any more code you want/need I can give it to you. (also I got the AnimDoneYet
method from Animator - Wait until animation finishes - Questions & Answers - Unity Discussions)
The wander method:
public void WanderPlayer(GameObject playerPos, Animator anim, NavMeshAgent agent, GameObject self)
{
agent.isStopped = false;
if (coru == false)
{
coru = true;
agent.SetDestination(GetDest(self));
}
anim.SetBool("walk", true);
if (agent.transform.position.magnitude == agent.destination.magnitude + 0.5f || agent.transform.position.magnitude == agent.destination.magnitude - 0.5f) // this is the if statement that is working weird
{
Debug.Log("this works");
state = State.Idle;
if (cro == null)
cro = StartCoroutine(AnimDoneYet(anim));
anim.SetBool("walk", false);
agent.ResetPath();
//agent.destination = new Vector3(self.transform.position.x, self.transform.position.y, self.transform.position.z);
}
}
IEnumerator AnimDoneYet(Animator anim)
{
yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length + anim.GetCurrentAnimatorStateInfo(0).normalizedTime);
}
private Vector3 GetDest(GameObject self)
{
chosenDest = new Vector3(self.transform.position.x + Random.Range(-30, 30), self.transform.position.y, self.transform.position.z + Random.Range(-30, 30));
checkedheight = Instantiate(invis, chosenDest, Quaternion.identity);
downRay = new Ray(checkedheight.transform.position, -transform.up);
upRay = new Ray(checkedheight.transform.position, transform.up);
if (Physics.Raycast(upRay, out hit) || Physics.Raycast(downRay, out hit))
{
if (hit.collider != null && hit.collider == CompareTag("Terrain"))
{
chosenDest.y = hit.collider.transform.position.y;
}
}
return chosenDest;
}