【问题标题】:Pathfinding to waypoints using NavMesh (Unity)使用 NavMesh (Unity) 寻找航路点
【发布时间】:2018-08-29 09:11:38
【问题描述】:

我想制作一个简单的脚本,将 NavMesh 代理引导到各种航路点。我是 Unity 的新手,所以我还不知道一些基本功能,而是输入伪代码。

using UnityEngine;
using UnityEngine.AI;

public class Path_left_blue : MonoBehaviour {

    private Transform target;
    private int wavepointindex = 0;
    public NavMeshAgent agent;

    void Start () {
        target = Waypoints_blue_left.waypoints[0];
    }

    void Update () {
        //Set destination to waypoint
        Vector3 dir = target.position;
        agent.setDestination(dir);

        if (agent is within a close range/touching target waypoint)

            //Remove object if at the last waypoint
            if (wavepointindex == Waypoints_blue_left.waypoints.Length)
                Destroy(gameObject);

            wavepointindex++;
            target = Waypoints_blue_left.waypoints[wavepointindex];

    }
}

【问题讨论】:

    标签: c# unity3d path-finding navmesh


    【解决方案1】:

    void Update() 函数调用每一帧。所以你需要一个函数来检查代理是否到达指向,将新的目的地设置给它。

    我将您的代码更改为:

    using UnityEngine;
    using UnityEngine.AI;
    
    public class Path_left_blue : MonoBehaviour 
    {
        private Transform target;
        private int wavepointindex = -1;
        public NavMeshAgent agent;
    
        void Start () 
        {
            EnemyTowardNextPos();
        }
    
        void Update () 
        {
            // agent is within a close range/touching target waypoint
            if (!agent.pathPending && agent.remainingDistance < 0.5f)
            {
                EnemyTowardNextPos();
            }
        }
    
        void EnemyTowardNextPos ()
        {
            if(wavepointindex == Waypoints_blue_left.waypoints.Length - 1)
            {
                Destroy(gameObject);
            }
            else
            {
                // set destination to waypoint
                wavepointindex++;
                target = Waypoints_blue_left.waypoints[wavepointindex];
                agent.SetDestination(target);
            }
        }
    }
    

    EnemyTowardNextPos() 函数仅在代理到达当前点时调用。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 1970-01-01
      • 2020-10-04
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      相关资源
      最近更新 更多