簡體   English   中英

我無法讓敵人團結一致地跟隨玩家

[英]I can't get the enemy to follow the player in unity

敵人首先走到玩家身上,然后停下來,不動。 chasePlayer函數每幀運行一次,因此敵人應該每幀更新其目的地,但這沒有發生,它會在第一個實例中執行,然后在到達第一個目的地時停止播放,不再向玩家發送。 我怎樣才能解決這個問題?

public class Slime : MonoBehaviour, IEnemy {
    public Transform enemyTarget;
    public float maxHealth, power, toughness;
    public float currentHealth;

    private NavMeshAgent navAgent;
    private Player player;

    void Start() {
        navAgent = GetComponent<NavMeshAgent> ();
        currentHealth = maxHealth;
    }

    void Update() {
        ChasePlayer();
    }

//Makes enemy chases player
    void ChasePlayer() {
        this.player = player;
        navAgent.SetDestination(enemyTarget.position);
        Debug.Log ("Chasing player");
    }
}

根據您的評論:

它會在第一個實例中執行此操作,然后在到達第一個目的地時停止播放,不再播放

在我看來,沒有刷新的是玩家位置。 因此,敵人只會在喚醒時檢查玩家的位置,然后移動到該地點,然后停止重新檢查。

嘗試以下操作,讓我們知道如何進行。 唯一的區別是它不是通過編輯器鏈接播放器,而是通過喚醒中的代碼鏈接。 我自己使用它,並且運行良好。

using UnityEngine;
using System.Collections;

public class Slime: MonoBehaviour
{
    Transform player;        // Ref to the player's position.
    NavMeshAgent nav;        // Ref to the nav mesh agent.

    void Awake ()
    {
        // Set up the references.
        player = GameObject.FindGameObjectWithTag ("Player").transform;
        nav = GetComponent <NavMeshAgent> ();
    }


    void Update ()
    {
        //Here it would be nice to add a stop condition, like when the player is dead or when it is out of range
        ChasePlayer();

    } 

    void ChasePlayer() {
        nav.SetDestination (player.position);
        Debug.Log ("Chasing player");
    }
}

我使用以下教程作為參考:

https://unity3d.com/learn/tutorials/projects/survival-shooter/enemy-one?playlist=17144

從問題的注釋中,我最初看到的是您試圖設置觸發敵人的行動范圍。 下面,我為您提供了一種計算兩個GameObject之間距離的可能方法,您可以將其添加到Update()中:

float dist = Vector3.Distance(player.position, transform.position)
if(dist < 10.0)
{
        ChasePlayer();
}

作為參考: https : //docs.unity3d.com/ScriptReference/Vector3.Distance.html

查看敵人目標的以下轉換。 請參閱此處的文檔: https : //docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html

請注意,您還可以使用將Vector2用於2D跟蹤的相同方法。

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    // The target marker.
    public Transform target;

    // Speed in units per sec.
    public float speed;

    void Update()
    {
        // The step size is equal to speed times frame time.
        float step = speed * Time.deltaTime;

        // Move our position a step closer to the target.
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }
}

我解決了這個問題。 我遇到這個問題的原因是因為玩家的模型只是不移動模型的玩家游戲對象的孩子,因此我更改了它,以便整個玩家移動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM