U3D基础之人工智能—敌人巡逻

    科技2022-08-10  145

    敌人巡逻

    首先在场景中创建几个巡逻的点,将玩家和敌人的Tag设置为相应的Tag 其中enemy的组件如下 在Enemy脚本中代码如下

    public class Enemy : MonoBehaviour { public float PatrolSpeed = 3f; public float PatrolWaitTime = 1f; public Transform PatrolWayPoints; private NavMeshAgent agent; private float PatrolTimer = 0f; private int wayPointsIndex = 0; private void Start() { agent = GetComponent<NavMeshAgent>(); } private void Update() { Patrolling(); } /// <summary> /// 巡逻函数 /// </summary> void Patrolling() { agent.isStopped = false;//首先将运动状态设置为运动 agent.speed = PatrolSpeed;//设置巡逻速度 if (agent.remainingDistance < agent.stoppingDistance)//如果已经到达目标点 { PatrolTimer += Time.deltaTime; if (PatrolTimer > PatrolWaitTime) { if (wayPointsIndex == PatrolWayPoints.childCount - 1) wayPointsIndex = 0; else wayPointsIndex++; PatrolTimer = 0; } } else PatrolTimer = 0; agent.destination = PatrolWayPoints.GetChild(wayPointsIndex).position; } }

    因为其中判断是否到达目标点涉及到距离的比较,需要将敌人的Stopping Distance设置一下,代表之间的冗余。

    Processed: 0.022, SQL: 8