【问题标题】:Unity NavMesh path reverseUnity NavMesh 路径反向
【发布时间】:2020-10-04 21:39:39
【问题描述】:

我需要反转这个用于制作游戏对象在一些变换之间巡逻的脚本。我需要对象从点 (1, 2, 3, 4, 5) 开始按顺序导航,当它到达数组的末尾时,它会反转数组本身的顺序,以便向后导航 (5, 4, 3, 2 ,1)。

using UnityEngine;
using UnityEngine.AI;
public class Patrol : MonoBehaviour
{

    public Transform[] points;
    private int destPoint = 0;
    private NavMeshAgent agent;


    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
        agent.autoBraking = false;
        GotoNextPoint();
    }


    void GotoNextPoint()
    {
        if (points.Length == 0)
            return;

        agent.destination = points[destPoint].position;
        destPoint = (destPoint + 1) % points.Length;
    }


    void Update()
    {
        if (!agent.pathPending && agent.remainingDistance < 0.5f)
            GotoNextPoint();
    }
}

【问题讨论】:

  • 将您的 +1 "(destPoint + 1)" 转换为变量 (desPoint + x)。声明 x = 1; 然后在分配你的 agent.destination 之前做 if (points.Length == 0) { x = x * -1}

标签: unity3d navmesh


【解决方案1】:

您应该在到达终点时使用Array.Reverse,以便在您的代码上轻松实现。

文档here。

将此代码添加到GoToNextPoint 的末尾。

destPoint++;
if (destPoint >= points.Length)
{
    Array.Reverse(points);
    destPoint = 0;
}

然后删除。

destPoint = (destPoint + 1) % points.Length;

【讨论】:

  • 感谢 Horothenic,它就像一个魅力。易于实施。我怀疑有一个“反向”组件可以使用,但我无法让它工作。
  • 虽然效率不高,但在同一个数组上上下移动的变量会更有效,以避免创建更多数组,但这有效,不会触发 Reverse无论如何,运行时很多,
  • 我认为Array.Reverse 已经采用现有数组“点”并将其反转,而不创建新数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 2016-03-18
  • 1970-01-01
相关资源
最近更新 更多