Version: 2018.1
Mover un Agente a una Posición clickeada por el Mouse (ratón)
El acoplamiento de Animación y Navegación

Hacer que un Agente Patrulle entre un conjunto de puntos

Muchos de los juegos tienen NPCs que patrullan automáticamente alrededor del área jugando. El sistema de navegación puede ser utilizado para implementar este comportamiento pero es un poco más involucrado que el pathfinding (encuentra camino) estándar - meramente utilizando el camino más corto entre dos puntos hace para una ruta de patrulla limitada y predecible. Nosotros podemos obtener un patrón de patrulla más convincente al mantener un conjunto de puntos claves que son “útiles” para el NPC para que pase a través de ellos y visitarlos en algún tipo de secuencia. Por ejemplo, en un laberinto, usted podría colocar puntos claves de patrullaje en intersecciones y esquinas para asegurar que el agente revise cada corredor. Para un edificio de oficinas, los puntos claves podrían ser las oficinas individuales y otros cuartos.

Un laberinto con puntos de patrullaje claves marcados
Un laberinto con puntos de patrullaje claves marcados

La secuencia ideal de puntos de patrullaje van a depender de la manera que usted quiere que los NPCs se comporten. Por ejemplo, va a probablemente simplemente visitar los puntos en un orden metódico mientras que un guardian humano podría intentar atrapar el jugador al utilizar un patron más aleatorio. El comportamiento simple del robot puede ser implementado utilizando el código mostrado abajo.

Los puntos de patrullaje son proporcionados al script utilizando un arreglo público de Transforms. Este arreglo puede ser asignado desde el inspector utilizando GameObjects para marcar la posición de los puntos. La función GotoNextPoint configura el punto de destino para el agente (que también lo empieza a mover) y luego selecciona el nuevo destino que será utilizado en el siguiente llamado. Como se mantiene, el código hace un ciclo entre los puntos en la secuencia que estos ocurren en el arreglo pero usted puede fácilmente modificar esto, digamos al utilizar Random.Range para escoger un indice del arreglo en aleatorio.

In the Update function, the script checks how close the agent is to the destination using the remainingDistance property. When this distance is very small, a call to GotoNextPoint is made to start the next leg of the patrol.

    // Patrol.cs
    using UnityEngine;
    using UnityEngine.AI;
    using System.Collections;


    public class Patrol : MonoBehaviour {

        public Transform[] points;
        private int destPoint = 0;
        private NavMeshAgent agent;


        void Start () {
            agent = GetComponent<NavMeshAgent>();

            // Disabling auto-braking allows for continuous movement
            // between points (ie, the agent doesn't slow down as it
            // approaches a destination point).
            agent.autoBraking = false;

            GotoNextPoint();
        }


        void GotoNextPoint() {
            // Returns if no points have been set up
            if (points.Length == 0)
                return;

            // Set the agent to go to the currently selected destination.
            agent.destination = points[destPoint].position;

            // Choose the next point in the array as the destination,
            // cycling to the start if necessary.
            destPoint = (destPoint + 1) % points.Length;
        }


        void Update () {
            // Choose the next destination point when the agent gets
            // close to the current one.
            if (!agent.pathPending && agent.remainingDistance < 0.5f)
                GotoNextPoint();
        }
    }
    // Patrol.js
    var points: Transform[];
    var destPoint: int = 0;
    var agent: NavMeshAgent;


    function Start() {
        agent = GetComponent.<NavMeshAgent>();

        // Disabling auto-braking allows for continuous movement
        // between points (ie, the agent doesn't slow down as it
        // approaches a destination point).
        agent.autoBraking = false;

        GotoNextPoint();
    }


    function GotoNextPoint() {
        // Returns if no points have been set up
        if (points.Length == 0)
            return;
            
        // Set the agent to go to the currently selected destination.
        agent.destination = points[destPoint].position;

        // Choose the next point in the array as the destination,
        // cycling to the start if necessary.
        destPoint = (destPoint + 1) % points.Length;
    }


    function Update() {
        // Choose the next destination point when the agent gets
        // close to the current one.
        if (!agent.pathPending && agent.remainingDistance < 0.5f)
            GotoNextPoint();
    }
Mover un Agente a una Posición clickeada por el Mouse (ratón)
El acoplamiento de Animación y Navegación