[英]Detect and follow the player
我開始了一個新游戲。我有一個敵人,當玩家與敵人保持一定距離時,他會攻擊。我的腳本有效,敵人跟隨玩家,但盡管我在那里設置了數字,它還是跟隨玩家。 只有在距離玩家足夠近后,我才需要敵人跟隨。 我有一個附着在敵人身上的空物體,上面有腳本。
我在統一社區答案中尋找答案並找到我在此鏈接中使用的腳本https://answers.unity.com/questions/274809/how-to-make-enemy-chase-player-basic-ai.html和我也用谷歌搜索過,但找不到任何正確的解決方案。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AIController : MonoBehaviour
{
public int AttackTrigger2;
public Transform Player;
public int MoveSpeed = 4;
public int MaxDist = 10;
public int MinDist = 5;
void Update()
{
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)
{
//Here Call any function U want Like Shoot at here or something
}
}
}
}
我的代碼沒有錯誤,他做了我需要的事情,但是我的玩家離開一定距離后,我需要敵人停止跟隨玩家。
我猜您鏈接的論壇中的下一個答案實際上可以解決您的問題。 問題只是簡單地復制和粘貼,而沒有理解為什么某些行為應該如此。 在這種情況下:
>= MinDist
意味着只要它大於或等於MinDist
,敵人就會跟隨玩家,在這種情況下為 5. 我猜你想要的是:
<= MaxDist
這樣敵人只有在距離小於 10 時才會跟隨。 如果距離超過 10,請停止關注。
if
情況下,您應該首先更改條件。 根據你的代碼敵人會跟隨玩家,如果他們之間的距離大於 MinDist。 將>=
替換為<=
。 我想你可能想要這樣的東西。
if (Vector3.Distance(transform.position, Player.position) <= MaxDist)//not MinDist
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if (Vector3.Distance(transform.position, Player.position) <= MinDist)//not MaxDist
{
//Here Call any function you want, like Shoot or something
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.