Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

    westergard

    Joined:
    May 4, 2015
    Posts:
    90
    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;
    4.  
    5. public class Patrol : MonoBehaviour
    6. {
    7.     public Transform[] pointsavisiter;
    8.     private int destPoint = 0;
    9.     private NavMeshAgent agent;
    10.  
    11.     void Start()
    12.     {
    13.         agent = GetComponent<NavMeshAgent>();
    14.         agent.autoBraking = false;
    15.         VaAuProchainPoint();
    16.     }
    17.  
    18.     void VaAuProchainPoint()
    19.     {
    20.         if (pointsavisiter.Length == 0)
    21.             return;
    22.         agent.destination = pointsavisiter[destPoint].position;
    23.         destPoint = (destPoint + 1) % pointsavisiter.Length;
    24.     }
    25.  
    26.     void Update()
    27.     {
    28.         if (!agent.pathPending && agent.remainingDistance < 0.5f)
    29.             VaAuProchainPoint();
    30.     }
    31. }
    32.  
    thanks a lot for your help!!

    Seb
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    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:
    Triggers: https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
    Raycast for LoS: https://docs.unity3d.com/ScriptReference/Physics.Raycast.html