Search Unity

Enemy AI patrolling, but i want it to detect player and follow it at a mindistance

Discussion in 'Scripting' started by westergard, May 3, 2019.

  1. westergard


    May 4, 2015
    Hello everyone.

    I have a script on an NPC that makes him patrol around a village. I'd like it to detect the player when it comes at a minimal distance and when it does, then direct himself to the player, but if the player gets away, i want it to return to it's patrol.

    I'm not sure where to start. Any script you know that would be a good start, or another thread you know... I've searched the forums but found nothing so far.

    Here is the patrol script i have for now:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.AI;
    3. using System.Collections;
    5. public class Patrol : MonoBehaviour
    6. {
    7.     public Transform[] pointsavisiter;
    8.     private int destPoint = 0;
    9.     private NavMeshAgent agent;
    11.     void Start()
    12.     {
    13.         agent = GetComponent<NavMeshAgent>();
    14.         agent.autoBraking = false;
    15.         VaAuProchainPoint();
    16.     }
    18.     void VaAuProchainPoint()
    19.     {
    20.         if (pointsavisiter.Length == 0)
    21.             return;
    22.         agent.destination = pointsavisiter[destPoint].position;
    23.         destPoint = (destPoint + 1) % pointsavisiter.Length;
    24.     }
    26.     void Update()
    27.     {
    28.         if (!agent.pathPending && agent.remainingDistance < 0.5f)
    29.             VaAuProchainPoint();
    30.     }
    31. }
    thanks a lot for your help!!

  2. GroZZleR


    Feb 1, 2015
    You're rarely going to find a script that just slips right into your project and does exactly what you need. Gamedev is all about engineering your own solutions.

    As for your problem, it looks like you have waypoint navigation up and running, so you just need the chase portion. Add a trigger collider to your guard, and if the player interacts with the collider, set your agent to an alerted state (probably want a line of sight check first) and begin chasing the player. If the guard loses sight of the player, give up after a set amount of time and return to patrolling.

    Here are the relevant docs that'll help you get started:
    Raycast for LoS: