Tutorial: un guardia que patrulla y persigue

Un enemigo que recorre una ronda y corre hacia el jugador cuando lo ve. Enseña navegación y línea de visión.

1. Preparación

Preparación
  1. Haz el guardia: una Capsule con un componente NavAgent. El nivel necesita suelo por el que el agente pueda caminar; la navegación tiene su propia página en Project Settings.
  2. Crea objetos vacíos llamados Post 1, Post 2, Post 3... donde deba patrullar. El script los recorre en orden.
  3. El jugador necesita la etiqueta Player.

2. El script

El script

Scripts/Guard.cs

public class Guard : Behaviour
{
    public float sight = 12f;
    public float chaseSpeed = 5f;
    public float walkSpeed = 2f;

    GameObject player;
    bool chasing;

    public override void Start()
    {
        player = GameObject.FindPlayer();
        Round();
    }

    void Round()
    {
        var posts = new System.Collections.Generic.List<Vector3>();
        for (int n = 1; GameObject.Find("Post " + n) != null; n++) posts.Add(GameObject.Find("Post " + n).transform.position);
        gameObject.agent.speed = walkSpeed;
        if (posts.Count > 0) gameObject.agent.Patrol(posts.ToArray(), 1.5f);
        chasing = false;
    }

    public override void Update(float deltaTime)
    {
        if (player == null) return;
        Vector3 eyes = transform.position + Vector3.up * 1.6f;
        Vector3 them = player.transform.position + Vector3.up * 1f;
        // seen: near enough, and nothing but the player on the line between the two
        bool near = Vector3.Distance(eyes, them) < sight;
        bool seen = near && (!Physics.Linecast(eyes, them, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject) || hit.gameObject == player);
        if (seen)
        {
            chasing = true;
            gameObject.agent.speed = chaseSpeed;
            gameObject.agent.SetDestination(player.transform.position);
        }
        else if (chasing && gameObject.agent.arrived)
        {
            // lost them: back to the round
            Round();
        }
    }
}

Guárdalo como Scripts/Guard.cs y añádelo al guardia.

3. Cómo funciona

Cómo funciona

4. Pruébalo

Pruébalo

Camina detrás de una pared y el guardia te pierde. Combínalo con vida: haz que el guardia dañe al jugador al tocarlo.

Siguiente: una torreta y sus balas.