Unity3D開發敵人自動攻擊和自動尋路
簡介:當製作動作類攻擊遊戲時,會用到敵人的自動攻擊及自動尋找攻擊目標,如何實現自動攻擊和自動尋路呢?下面簡單的講解我對這方面的理解。
當你已經匯入了敵人的模型並製作好了敵人動畫控制狀態機,接下來肯定會想讓敵人具備攻擊和尋找目標的能力,要開發這一功能,其實只需要做兩件事情:
第一:通過CharacterController控制移動,即通過呼叫SimpleMove(Vector3)移動。
第二:根據主角的位置和距離,判斷是否進行攻擊,攻擊的時候利用隨機數來發起攻擊動畫的選擇。
編寫指令碼:Enimy.cs
using UnityEngine;
usingSystem.Collections;
publicclassEnimy : MonoBehaviour {
// Use this for initialization
privateTransform player;
publicfloat attackDistance = 2;//這是攻擊目標的距離,也是尋路的目標距離
privateAnimator animator;
publicfloat speed;
privateCharacterController cc;
publicfloat attackTime = 3;//設定定時器時間 3秒攻擊一次
privatefloat attackCounter = 0;
voidStart () {
player = GameObject.FindGameObjectWithTag("Player").transform;
cc = this.GetComponent<CharacterController>();
animator = this.GetComponent<Animator>();//控制動畫狀態機中的奔跑動作呼叫
attackCounter = attackTime;//一開始只要抵達目標立即攻擊
}
// Update is called once per frame
voidUpdate () {
Vector3 targetPos =player.position;
targetPos.y = transform.position.y;//此處的作用將自身的Y軸值賦值給目標Y值
transform.LookAt(targetPos);//旋轉的時候就保證已自己Y軸為軸心旋轉
float distance = Vector3.Distance(targetPos,transform.position);
if (distance <= attackDistance)
{
attackCounter += Time.deltaTime;
if (attackCounter >attackTime)//定時器功能實現
{
int num = Random.Range(0, 2);//攻擊動畫有兩種,此處就利用隨機數(【0】,【1】)切換兩種動畫
if (num == 0)animator.SetTrigger("Attack1");
else animator.SetTrigger("Attack2");
attackCounter = 0;
}
else
{
animator.SetBool("Walk", false);
}
}
else
{
attackCounter = attackTime;//每次移動到最小攻擊距離時就會立即攻擊
if(animator.GetCurrentAnimatorStateInfo(0).IsName("EnimyWalk"))//EnimyWalk是動畫狀態機中的行走的狀態
cc.SimpleMove(transform.forward*speed);
animator.SetBool("Walk ",true);//移動的時候播放跑步動畫
}
}
}
結合上面的註釋,是不是很清楚這些功能的實現原理了,至少當我忘記的時候看到這個筆記就會明白了。有問題可以留言,一起交流學習。