我将如何在代码后的 AI 中实现 navmesh 寻路。 C#统一

How would I implement navmesh pathfinding into this AI following code. C# Unity

我有这段代码可以让敌人跟随我的玩家(并攻击等),但我不确定如何将导航网格添加到其中以便它可以导航障碍物。目前,它继续前进并卡在墙壁和障碍物上。 我以前从未使用过navmesh。

我将如何在这段代码中实现 navmesh 寻路。

谢谢。

using UnityEngine;
using System.Collections;

public class wheatleyfollow : MonoBehaviour {

    public GameObject ThePlayer;
    public float TargetDistance;
    public float AllowedRange = 500;
    public GameObject TheEnemy;
    public float EnemySpeed;
    public int AttackTrigger;
    public RaycastHit Shot;

    void Update() {
        transform.LookAt (ThePlayer.transform);
        if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), out Shot)) {
            TargetDistance = Shot.distance;
            if (TargetDistance < AllowedRange) {
                EnemySpeed = 0.05f;
                if (AttackTrigger == 0) {
                    transform.position = Vector3.MoveTowards (transform.position, ThePlayer.transform.position, EnemySpeed);
                }
            } else {
                EnemySpeed = 0;
            }
        }

        if (AttackTrigger == 1) {
            EnemySpeed = 0;
            TheEnemy.GetComponent<Animation> ().Play ("wheatleyattack");
        }
    }

    void OnTriggerEnter() {
        AttackTrigger = 1;
    }

    void OnTriggerExit() {
        AttackTrigger = 0;
    }

}

开始时,我们需要 NavMeshAgent 保存此脚本的对象,然后我们将保存对代理的引用。我们还需要一个 NavMeshPath 来存储我们的路径(这不是一个可附加的组件,我们将在代码中创建它)。

我们需要做的就是使用 CalculatePathSetPath 更新路径。您可能需要对代码进行一些微调,但这是最基本的。您可以使用 CalculatePath 生成路径,然后决定是否要使用 SetPath.

执行该路径

注意: 我们可以使用 SetDestination,但是如果你有很多 AI 单元,如果你需要即时路径,它会变得很慢,这就是为什么我通常使用 CalculatePathSetPath.

现在剩下的就是制作您的导航网格 Window -> Navigation。在那里你可以微调你的代理和区域。一个必需的步骤是在 Bake 选项卡中烘焙网格。

Unity 支持预制件和其他组件上的导航网格,但是,这些组件尚未内置到 Unity 中,因为您需要 download 将它们添加到您的项目中。

如您所见,您的所有速度和移动都已被移除,因为它现在由您的 NavMeshAgent 控制。

using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class wheatleyfollow : MonoBehaviour {

  public GameObject ThePlayer;
  public float TargetDistance;
  public float AllowedRange = 500;
  public GameObject TheEnemy;
  public int AttackTrigger;
  public RaycastHit Shot;

  private NavMeshAgent agent;
  private NavMeshPath path;

  void Start() {
    path = new NavMeshPath();
    agent = GetComponent<NavMeshAgent>();
  }

  void Update() {
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot)) {
      TargetDistance = Shot.distance;
      if (TargetDistance < AllowedRange && AttackTrigger == 0) {
        agent.CalculatePath(ThePlayer.transform.position, path);
        agent.SetPath(path);
      }
    }
    if (AttackTrigger == 1) {
      TheEnemy.GetComponent<Animation>().Play("wheatleyattack");
    }
  }

  void OnTriggerEnter() {
    AttackTrigger = 1;
  }

  void OnTriggerExit() {
    AttackTrigger = 0;
  }

}

旁注:您应该删除任何未使用的 using,因为这会使您的最终构建膨胀。