Tutoriel : un garde qui patrouille et poursuit

Un ennemi qui fait une ronde et court vers le joueur quand il le voit. Il enseigne la navigation et la ligne de vue.

1. Préparation

Préparation
  1. Faites le garde : une Capsule avec un composant NavAgent. Le niveau a besoin d'un sol sur lequel l'agent peut marcher ; la navigation a sa propre page dans Project Settings.
  2. Créez des objets vides nommés Post 1, Post 2, Post 3... là où il doit patrouiller. Le script les parcourt dans l'ordre.
  3. Le joueur a besoin du tag Player.

2. Le script

Le 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();
        }
    }
}

Enregistrez-le sous Scripts/Guard.cs et ajoutez-le au garde.

3. Comment ça marche

Comment ça marche

4. Essayer

Essayer

Marchez derrière un mur et le garde vous perd. Combinez avec vie : faites blesser le joueur par le garde quand il le touche.

Suite : une tourelle et ses balles.