在設計敵人AI時可以先製作基礎的能力像是攻擊、閃避、追蹤玩家或者進行其他動作,要達成這些功能可以透過Enum和StartCoroutine來實現。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyControl : MonoBehaviour
{
public enum EnemyBehavior {patrol,battle};
public EnemyBehavior EnemyNow;
public float speed;
private Transform mytransform;
private Transform playertransform;
private SpriteRenderer spr;
void Start()
{
EnemyBehavior = Status.patrol;
spr = this.transform.GetComponent<SpriteRenderer>();
mytransform = this.transform;
if (GameObject.Find("player") != null)
{
playertransform = GameObject.Find("player").transform;
}
StartCoroutine(DoCheck());
}
private void FixedUpdate() ...
}
//偵測功能
bool PlayerCheck()
{
if (Mathf.Abs(mytransform.position.x - playertransform.position.x) < 4f)
{
//當玩家和敵人距離小於4時回傳true進入戰鬥
return true;
}
return false;
}
IEnumerator DoCheck()
{
for (; ; )
{
if (PlayerCheck())
{
EnemyNow = EnemyBehavior.battle;
}
yield return new WaitForSeconds(.1f);
}
}
參考資料:
https://www.youtube.com/watch?v=pQ9Fabgvusk&t=6s