教程:巡逻并追击的守卫
一个敌人,沿路线巡逻,看到玩家就冲过去。它教你导航和视线。
1. 准备

- 做守卫:一个带 NavAgent 组件的 Capsule。关卡里需要智能体可以行走的地面;导航在 Project Settings 中有单独的页面。
- 在它应当巡逻的地方建几个空对象,命名为
Post 1、Post 2、Post 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. 工作原理

Round收集所有名为Post 1、Post 2……的对象,让智能体Patrol(巡逻)它们,每处停留 1.5 秒。- 每帧守卫检查能否看到玩家:距离够近(
sight),并且从它的眼睛到玩家的连线上除了玩家没有别的东西(Physics.Linecast)。所以墙可以挡住玩家。 - 看到了:它朝玩家冲去(
chaseSpeed)。跟丢了:到达原本要去的地方后,回到巡逻路线。
4. 试一试

走到墙后面,守卫就会跟丢你。结合生命值:让守卫碰到玩家时伤害他。
下一步:炮塔和子弹。