生活随笔
收集整理的這篇文章主要介紹了
unity敌人的巡逻
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?在unityunity游戲開發過程中,敵人、怪物的自動巡邏肯定是無法避免的,今天主要講 給敵人和怪物設置定點巡邏。
在給怪物、敵人設置頂點巡邏的時候需要引入命名空間using UnityEngine.AI;
public class Spider : MonoBehaviour {private NavMeshAgent agent;//給怪物添加制動巡航組件private Animator an;//獲取新動畫public Transform[] waypoints;//創建一個對象數組,把需要導航的位置存入進去private int index = 0;private float timer = 0;private float times = 3;private Transform player;// Use this for initializationvoid Start () {agent = GetComponent<NavMeshAgent>();//an = GetComponent<Animator>();agent.destination = waypoints[index].position;player = GameObject.FindWithTag("Player").transform;}// Update is called once per framevoid Update () {float dir = Vector3.Distance(player.position, transform.position);//獲取玩家距離敵人的距離if(dir > 2 && dir < 5)//追蹤{Track();}else if(dir <= 2)//攻擊{Attack();}else{Patrol();}}void Track(){//transform.LookAt(player.position);//給定條件看向玩家 這行代碼可以不用agent.SetDestination(player.position);//自動導航到玩家的位置}void Attack()//攻擊{agent.ResetPath();//停止導航transform.LookAt(player.position);an.SetTrigger("Attack");}void Patrol()//自動導航{if (agent.remainingDistance < 0.5f)//在自動巡航到0.5m后進入這個判斷條件{an.SetInteger("walk",0);timer += Time.deltaTime;if (timer >= times){timer = 0;index++;index %= 4;//給怪物巡邏幾個點位就給幾agent.SetDestination(waypoints[index].position);//繼續網下一個位置導航}}else{an.SetInteger("walk", 1);//播放動畫}}
}
這里寫了怪物自動巡邏,當玩家靠近到一定距離,停止巡邏,走向玩家,叫指定范圍,敵人開始攻擊玩家。
總結
以上是生活随笔為你收集整理的unity敌人的巡逻的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。