Unity のナビゲーションシステム 追記

始めに

Unity のナビゲーションシステム の追記

使い方が分からず悩んでしまった事を書きます。

問題

NavMesh は便利ではあるもののGameObjectとべったりくっついており、Entitiesと組み合わせられないというのがあります。

移動はEntitiesで行い、パス計算だけ利用しようとしましたが上手くいきません。

現在位置の座標を設定しているのに、毎回初期配置位置から計算されてしまいます。

解決方法

現在位置は transform.position ではなく NavMeshAgent.Warp で設定する。

サンプルコード

using UnityEngine;
using UnityEngine.AI;

public class PathFinderAgent : MonoBehaviour
{
    NavMeshAgent navMeshAgent;

    public void Setup()
    {
        navMeshAgent = GetComponent<NavMeshAgent>();
        navMeshAgent.updatePosition = false;
        navMeshAgent.updateRotation = false;
    }

    public bool StartFindPath(Vector3 from, Vector3 to)
    {
        navMeshAgent.ResetPath();
        navMeshAgent.Warp(from);
        return navMeshAgent.SetDestination(to);
    }

    public void Stop()
    {
        navMeshAgent.ResetPath();
        navMeshAgent.isStopped = true;
    }

    public bool TryGetFindedPath(out Vector3[] path)
    {
        if (navMeshAgent.pathPending)
        {
            path = null;
            return false;
        }
        path = navMeshAgent.path.corners;
        return true;
    }

    void Start()
    {
        Setup();
        StartFindPath(Vector3.zero, new Vector3(100f, 0f, 0f)); // TODO (現在地点,目標地点)
    }

    void Update()
    {
        if (TryGetFindedPath(out var path))
        {
            // TODO 計算されたパスを使う
        }
    }
}

注意点

インスペクタ

インスペクタ

最後に

Entities を立ち上げたからにはそのうち対応APIが出てくるとは思います。

このページが無駄になって欲しいですね。

top