我有这个代码,让敌人跟随我的玩家(和攻击等),但我不知道如何添加导航网,以便它可以通过障碍。目前,它继续前进,被堵在墙上和障碍物上。我以前从没用过肚脐。
我将如何在此代码中实现导航路径查找。
谢谢。
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;
}
}发布于 2018-06-16 14:58:14
首先,我们将在包含此脚本的对象上要求一个NavMeshAgent,然后保存对代理的引用。我们还需要一个NavMeshPath来存储我们的路径(这不是一个可附加的组件,我们将在代码中创建它)。
我们所需要做的就是使用CalculatePath和SetPath更新路径。您可能需要微调一些代码,但这是最基本的。您可以使用CalculatePath生成一个路径,然后决定是否要使用SetPath执行该路径。
注:我们可以使用SetDestination,但是如果你有很多AI单位,如果你需要即时路径,它可能会变慢,这就是为什么我通常使用CalculatePath和SetPath。
现在剩下的就是让你的导航网Window -> Navigation。在那里你可以对你的代理人和区域进行调查。一个必要的步骤是在Bake选项卡中烘焙网格。
统一支持预制件和其他组件上的导航,但是这些组件还没有内置到统一中,因为您需要将它们下载到您的项目中。
如您所见,所有的速度和运动都已被移除,因为它现在是由您的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,因为这会使你的最终构建变得臃肿。
https://stackoverflow.com/questions/50886239
复制相似问题