延續昨天的敵人AI製作,今天要做敵人追蹤玩家位置並朝玩家靠近的功能
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyControl : MonoBehaviour
{
public enum EnemyBehavior {patrol,battle};
public EnemyBehavior EnemyNow;
//戰鬥狀態
public enum Battle { follow, attack, dodge };
public Battle BatChoose;
//確認面對的方向
public enum checkface { Lelf,Right};
public checkface face;
public float move;
public float speed;
private bool LookForP;
private float SwichCheck;
private Transform mytransform;
private Transform playertransform;
private SpriteRenderer spr;
private Rigidbody2D rig;
void Start()
{
EnemyBehavior = Status.patrol;
spr = this.transform.GetComponent<SpriteRenderer>();
spr = this.transform.GetComponent<SpriteRenderer>();
//面對的方向
if (spr.flipX )
{
face = checkface.Right;
}
else {
face = checkface.Lelf;
}
mytransform = this.transform;
if (GameObject.Find("player") != null)
{
playertransform = GameObject.Find("player").transform;
}
if (!LookForP && playertransform)
{
StartCoroutine(DoCheck());
}
}
private void FixedUpdate() ...
}
private void FixedUpdate()
{
//敵人狀態
switch (EnemyNow)
{
case EnemyBehavior.patrol:
if (playertransform)
{
//巡邏
Domove();
}
break;
case EnemyBehavior.battle:
switch (BatChoose)
{
case Battle.follow:
followPlayer();
break;
case Battle.attack:
break;
}
break;
}
}
void followPlayer()
{
if (playertransform)
{
if (mytransform.position.x >= playertransform.position.x)
{
spr.flipX = false;
face = checkface.Lelf;
}
else
{
spr.flipX = true;
face = checkface.Right;
}
switch (face)
{
case checkface.Lelf:
if(Mathf.Abs(mytransform.position.x - playertransform.position.x) >= 4f)
mytransform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
break;
case checkface.Right:
if(Mathf.Abs(mytransform.position.x - playertransform.position.x) >= 4f)
mytransform.position += new Vector3(speed * Time.deltaTime, 0, 0);
break;
}
}
else
{
BatChoose = Battle.attack;
}
}
待更
協程Coroutine的用法我還不是很熟練所以巡邏移動時有BUG,之後研究完把code修好再更新
參考資料:
https://www.youtube.com/watch?v=pQ9Fabgvusk&t=6s