public override void OnStateEnter(Animator animator, AnimatorStateInfo animatorStateInfo, int layerIndex) { if (navAgent == null) { navAgent = animator.GetComponent <NavMeshAgent>(); } if (target == null) { target = PlayerExample.GetInstance(); } //Reset path upon entering chase state so we have a fresh one towards the target navAgent.ResetPath(); navAgent.speed = runSpeed; }
//Tries RepathCount times to find a path near the player, increasing the radius each time. //This is needed in case the player is not on valid Navmesh public void SetDestinationNearTarget(NavMeshAgent _agent, PlayerExample _target) { NavMeshHit hit; float radius = 0; for (int i = 0; i < repathCount; ++i) { Vector3 randomPosition = Random.insideUnitSphere * radius; randomPosition += _target.transform.position; if (NavMesh.SamplePosition(randomPosition, out hit, radius, 1)) { _agent.SetDestination(hit.position); break; } else { ++radius; } } }
//Check if we are within chase range of the target, is static to be used by other states public static bool ShouldChasePlayer(Vector3 _chaserPosition) { PlayerExample player = PlayerExample.GetInstance(); return((player.transform.position - _chaserPosition).sqrMagnitude < chaseRadius * chaseRadius); }