unity_小功能实现(敌人巡逻功能)
?
利用NavMeshAgent控制敵人巡邏,即敵人在一組位置間循環巡邏。
?
首先我們要知道NavMeshAgent中有兩個方法:1.鎖定當前巡邏的某一目標位置,即navMeshAgent.destination
?
2.到達目標位置停止巡邏(休息一定時間繼續巡邏),即navMeshAgent.Stop();
?
代碼實現如下:
?
usingUnityEngine;
usingSystem.Collections;
using UnityEngine.AI;
?
public class EnemyMoveAI : MonoBehaviour {
?
public Transform[] directPoints; //0-3
privateint index = 0;
??? public float patroTime = 3f;//到達某一點停止等待時間
??? private float timer = 0;//計時器
?
privateNavMeshAgentnavMeshAgent;
?
?
void Awake()
??? {
navMeshAgent = GetComponent<NavMeshAgent>();
navMeshAgent.destination = directPoints[index].position;
??? }
?
void Update()
??? {??
if (navMeshAgent.remainingDistance< 0.5f)
??????? {
timer += Time.deltaTime;
if (timer==patroTime)
??????????? {
index++;
??????????????? index %= 4;//在4個點之間循環巡邏
timer = 0;
navMeshAgent.destination = directPoints[index].position;
??????????? }
??????? }
??? }
?
}
?
注意:
?
1.為了保證敵人能在該組點內循環巡邏(而不是只巡邏一圈),采用取余的方式獲得點數組的下標。
?
2.沒有使用navMeshAgent.Stop();原因是,如果使用了則到達一個巡邏點后敵人將不會再向新的目標點移動。
轉載于:https://www.cnblogs.com/shirln/p/9105556.html
總結
以上是生活随笔為你收集整理的unity_小功能实现(敌人巡逻功能)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何利用腾讯元宝设计课程?
- 下一篇: 腾讯元宝为何在特定领域表现出色?