I have the enemy following a patrol route using 2 waypoints and a Raycast. Would there be a way to get the enemy to stop following the route and start following the player when it is inside the radius? But if the player gets outside the radius, the enemy stops following and goes back to the route?
This is my patrol script:
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour
{
public Transform[] Waypoints;
public float Speed;
public int curWayPoint;
public bool doPatrol = true;
public Vector3 Target;
public Vector3 MoveDirection;
public Vector3 Velocity;
private NavMeshAgent agent;
void OnTriggerEnter(){
agent.SetDestination (Target);
}
void Update()
{
agent = GetComponent<NavMeshAgent>();
agent.SetDestination (Target);
{
agent.SetDestination (Target);
}
if (curWayPoint < Waypoints.Length)
{
Target = Waypoints[curWayPoint].position;
MoveDirection = Target - transform.position;
Velocity = rigidbody.velocity;
if(MoveDirection.magnitude < 1)
{
curWayPoint++;
}
else
{
Velocity = MoveDirection.normalized * Speed;
}
}
else
{
if(doPatrol)
{
curWayPoint=0;
}
else
{
Velocity = Vector3.zero;
}
}
rigidbody.velocity = Velocity;
transform.LookAt (Target);
}
}
One thing you could do is have the enemy periodically check its distance to the player. If the distance is within a certain amount it ignores its patrol. I think that would be a simpler solution as the only thing you seem to care about is if the enemy is within a certain distance. No need to worry about sphere colliders or triggers in this situation I think.
Not really. The simplest solution to this is to have the enemy find the player object, check the distance between the two, and then make a decision based on the distance. The trigger is an alternate solution but the issue there is that it is likely more expensive on processor resources. That however is an optimization thing and if you’re just one person making a game by yourself it isn’t likely that you’ll tax the processor that badly. Both solutions will function properly.
So, I’ve tried to get it to work a ton of times attempting to use the sphere trigger and I cannot get it to work. I seem to be having a problem with it not colliding for one, and for two I have no clue how I would get it to change paths.
How I know that it is not colliding is that I set a Debug.Log to send me a message when I collide with it and it is not sending anything.
The distance check is better for a single pair. But if you are going to do this on multiple units the space partitioning done by the physics engine will make sphere triggers cheaper.