1
因此,目前的代碼如何工作,敵人會發現玩家並向他移動。當他找到他時,他會停下來然後開始進攻。如果玩家離開,敵人將會停止攻擊並坐在那裏直到玩家回到距離範圍內。我該如何解決這個問題,以便當玩家移出射程時,敵人開始追擊,然後正常攻擊?如何修復我的追逐/攻擊代碼?
float moveSpeed = 3f;
float rotationSpeed = 3f;
float attackThreshold = 3f; //distance within which to attack
float chaseThreshold = 10f; //distance within which to start chasing
float giveUpThreshold = 20f; //distance beyond which AI gives up
float attackRepeatTime = 1f; //time between attacks
bool attacking = false;
bool chasing = false;
float attackTime;
Transform target; //the enemy's target
Transform myTransform; //current transform data of the enemy
void Update()
{
//rotate to look at the player
float distance = (target.position - myTransform.position).magnitude;
if (chasing)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
}
//move towards the player
if (chasing == true && attacking == false)
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
//give up if too far away
if (distance >= giveUpThreshold)
{
chasing = false;
// attacking = false;
}
//attack, if close enough, and if time is OK
if (distance <= attackThreshold && Time.time >= attackTime) //if attacking we want to stop moving
{
//attack here
bossAttack.Attack();
attackTime = Time.time + attackRepeatTime;
print("Attacking!");
attacking = true;
// anim.SetTrigger("AutoAttack");
chasing = false;
}
else
{
//not currently chasing.
//start chasing if target comes close enough
if (distance <= chaseThreshold) //if he gets to chase, and then you move out of range again, he won't chase again. he will only attack if comes into range again
{
chasing = true;
// attacking = false;
// print("Chasing!");
}
}
}
我認爲這就是所有必要的相關代碼。
其中一些我不能添加其他東西,因爲那樣的敵人將繼續追逐甚至超過門檻。 我甚至在 if if(distance> = chaseThreshold && distance <= giveUpThreshold)中加入 { attack = false; } 然後未註釋 如果(距離> = giveUpThreshold) { 追逐= FALSE; 攻擊=假; } 所以我仍然在某處失蹤,但我找不到它 –