教程:巡逻并追击的守卫

一个敌人,沿路线巡逻,看到玩家就冲过去。它教你导航和视线。

1. 准备

准备
  1. 做守卫:一个带 NavAgent 组件的 Capsule。关卡里需要智能体可以行走的地面;导航在 Project Settings 中有单独的页面。
  2. 在它应当巡逻的地方建几个空对象,命名为 Post 1、Post 2、Post 3……脚本按顺序走过它们。
  3. 玩家需要标签 Player。

2. 脚本

脚本

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

保存为 Scripts/Guard.cs,加到守卫上。

3. 工作原理

工作原理

4. 试一试

试一试

走到墙后面,守卫就会跟丢你。结合生命值:让守卫碰到玩家时伤害他。

下一步:炮塔和子弹。