我将如何在以下代码中实现导航网格寻路到此 AI 中.C# Unity



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

我将如何在此代码中实现导航网格路径查找。

谢谢。

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 中,因为您需要将它们下载到项目中。

如您所见,您的所有速度和移动都已被删除,因为它现在由您的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,因为这会使您的最终构建膨胀。

最新更新