NavMesh.SamplePosition

Searched and found a few unresolved threads but now answers, does NavMesh.SamplePosition work?

Trying this, to get a point on a specific Area Mask but it retruns an area on a different Area Mask. I have the

 NavMeshHit hit;
            Debug.Log(NavMesh.GetAreaFromName(areaName) + " NavMesh.GetAreaFromName(areaName))");
            if (NavMesh.SamplePosition(randomPoint, out hit, range, NavMesh.GetAreaFromName(areaName)))//-1 << areaIndex))
                {
                    setVector3Variable.Value = hit.position;
                }

Any ideas of if I’m doing something wrong of are there still issues withi this?

Thanks
Nathan

Sample position does work - it will return the closest point on a NavMesh with the given area mask. If you can provide more information about the specifics of your problem it would help provide a better answer. I don’t fully understand what you are trying to do or the result you are getting

Hey, thanks

I’m trying to write a Behaviour Tree node for apoligies for the slightly modifed code with things like .value and SharedVector3.

I’m trying to write a node that checks the npcs position relative to a pathway navmesh and return the closest point along that navmesh. The problem is that this is not returning a point on that navment but a raondom point elsewhere.

What i have is

 //[Tooltip("The Vector3 to get the values of")]
        private SharedVector3 getVector3Variable;
        public SharedGameObject m_TargetGameObject;
        [Tooltip("The Vector3 to set the values of")]
        public SharedVector3 setVector3Variable;
        public float range = 10.0f;
        private GameObject target;
       
        public string areaName;
        public override void OnStart()
        {
            target = GetDefaultGameObject(m_TargetGameObject.Value);
        }
            public override TaskStatus OnUpdate()
        {
            for (int i = 0; i < 1000; i++)
            {
                getVector3Variable = target.transform.position;
                Vector3 tempVector = new Vector3(getVector3Variable.Value.x, getVector3Variable.Value.y, getVector3Variable.Value.z);
                Vector3 randomPoint = tempVector + Random.insideUnitSphere * range;
                NavMeshHit hit;
                Debug.Log(NavMesh.GetAreaFromName(areaName) + " NavMesh.GetAreaFromName(areaName))");
                if (NavMesh.SamplePosition(randomPoint, out hit, range, NavMesh.GetAreaFromName(areaName)))
                {
                    setVector3Variable.Value = hit.position;
                    return base.OnUpdate();
                }
            }
          
            return base.OnUpdate();
        }
    }

I see you are sampling within, by default, a random point inside a unit circle * 10. Then you are NavMesh.SamplePositioning again with a radius of 10. This can give you wildly random results.

In the attached image assuming the orange dot is your getVector3Varabile.value, the orange circle represents the possible radius you are choosing random points within. The green dot represents the offset after you do the randomPoint with Random.insideUnitSphere * range. Finally the green circle represents the possible outcome from a NavMesh.SamplePosition with the same radius.

If you want to find a location on the NavMesh closest to the provided point, I would just NavMesh.SamplePosition on the point with a small radius. Unity recommends using at most 2x the agent height for performance.

Unless your target can move very far off a NavMesh, you should have no issues choosing the same, or very similar location to the target’s location.

7441379--912254--Example.png

1 Like

Thanks Chris,

I should have been more explicit in what I am attempting, I’m sorry for being so vague.

Basically, I have multiple navmesh in my scene and I’m trying to make a system where an agent can move from one to another. I am able to change the Agent Area easily.

What I am struggling with is that I have a pathway system of raods made with RAM and getting my npc to find the closest point on that pathway navmesh when they are off it. I have exported these as meshes and then baked all the roads as a “Pathway” navmesh. So, now say I have two other navmesh, a camp and a field. If my NPC is in the camp Navmesh and I want them to travel along the pathway to the closest point on the field navmesh I would hope to do two checks. When they are in the camp do a check for the closest point along the pathway and then walk to that, then do a seach for the closest point on the pathway navmesh to the field navmesh.

Perhaps this is not possible and I am trying to use the SamplePosition incorrectly. I’ll try out your suggestions and report back.

Thanks again for your time and help
Nathan

OK, so I think I’m using the wrong function,

 NavMeshHit hit;
            if (NavMesh.FindClosestEdge(transform.position, out hit, NavMesh.GetAreaFromName(areaName)))
            {
                setVector3Variable.Value = hit.position;
}

I’m thinking that this should work in returning the closest point on the specified navmesh but it’s not. My NPC still wanders in random directions.

Nah, that wasn’t it, I believe that that returns the closest point on the navmesh the agent is on. Think something alongs these lines is what I want but I’m still just returning random points that are not on the desired navmesh.

I feel like there is someting obvious I can’t get through my head but I just don’t know what it is.

public override TaskStatus OnUpdate()

{
getVector3Variable = target.transform.position;
Vector3 tempVector = new Vector3(getVector3Variable.Value.x, getVector3Variable.Value.y, getVector3Variable.Value.z);

NavMeshHit hit;
Debug.Log(NavMesh.GetAreaFromName(“Walkable”) + " NavMesh.GetAreaFromName(Walk");
Debug.Log(NavMesh.GetAreaFromName(areaName) + " NavMesh.GetAreaFromName(areaName))");
for (int i = 0; i < 1000; i++)
{
Vector3 randomPoint = tempVector + Random.insideUnitSphere * range;
if (NavMesh.SamplePosition(randomPoint, out hit, 2, NavMesh.GetAreaFromName(areaName)))
{
setVector3Variable.Value = hit.position;
break;
}
Debug.Log(i + “IIIIII”);
}
return base.OnUpdate();
}

Here is a screen grab of the current terrain I am working with. The blue is the normal “Walkable” Navmesh, the Purple is the “Pathway” Navmesh.

With Unity’s Navmesh system is there a way that if my player is on the “Walkable” navmesh that they do a check to find the closest point on the “Pathway” navmesh?

!(http://


Thanks in advance,
Nathan)

While I haven’t specifically used the FindClosestEdge you mentioned, I do believe that is a way you can achieve that, provided the Area Masks are configured correctly. I will reproduce a similar scene to see if I can provide you with some concrete advice on how to make it work.

Hey nathanjams,

I wanted to make sure I understood what you were doing correctly. Some of your posts mention multiple NavMeshes, which would actually require you connect them with a NavMeshLink, and possibly (depending on your bake settings) that you change the NavMeshAgent’s type to swap between being able to walk on one NavMesh or the other, since all NavMeshes using the NavMesh Components are bound to an Agent Type.
It’s really important to understand the difference between the NavMesh area and a separate NavMesh.
More info on the manual about it here: https://docs.unity3d.com/Manual/class-NavMeshSurface.html

It is probably more convenient to manage the road as a different NavMesh Area.
Swapping a NavMeshAgent over to totally different NavMeshes requires a NavMeshLink component to allow the agent to traverse between them, but you still have to consider swapping the Agent’s type there which ends up having other ramifications as well (such as possibly inconsistent agent radiuses for the bake).

If you are able to swap to a single NavMesh baked per NavMeshAgent and have the road configured as a different NavMeshArea, you can use **FindClosestEdge **as you were trying to do before.
The example code below requires that you have only 1 NavMesh with multiple NavMeshAreas, configured via NavMeshModifiers / NavMeshModifierVolumes.

However if you do want to keep 2 separate NavMeshes still, FindClosestEdge also accepts a NavMeshQueryFilter which could be used in place of the NavMesh.GetAreaFromName(“Water”) that would find the closest edge on a separate NavMesh as well. You just have to pass it the Agent ID used to bake the second NavMesh.

I set up a scene to replicate it that looks like this:


The blue area is configured to be the Water layer, everything else is Walkable.:
7455674--914882--upload_2021-8-28_5-58-37.png

I’ve attached a very simple script to the Agent that shows a button that, when clicked, will make the agent go to the blue area.

using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class GoToWater : MonoBehaviour
{
    private NavMeshAgent Agent;

    private void Awake()
    {
        Agent = GetComponent<NavMeshAgent>();
    }

    private void OnGUI()
    {
        if (GUI.Button(new Rect(20, 20, 300,50), "Go To Water"))
        {
            if (NavMesh.FindClosestEdge(Agent.transform.position, out NavMeshHit hit, NavMesh.GetAreaFromName("Water")))
            {
                Debug.Log("Found closest edge at: " + hit.position);
                Agent.SetDestination(hit.position);
            }
            else
            {
                Debug.Log("Could not find closest edge");
            }
        }
    }
}
2 Likes

whoa!

Thanks so much @ChrisKurhan

I’m ging to look into this right now. I’ll let you know how I go.

And again. Thank you!

Ok, first of all a massive thank you Chris for doing this and all of your time with walking me through this.

You are correct that I was using multiple NavmeshSurface components in the scene, each for a different area. So, I finally got my head around Modifiers and now have a single navmesh with different areas. It’s much better than what I was doing.

I am able to get the NavMesh.FindClosestEdge to work but only if the agent is close to the other navmesh, within 10 units. Any farther than that and it fails and chooses a seemingly random value. Are you aware of any way to adjust the search distance value?

I’ve tried to create a spiral pattern from my player’s poisition while doing a check but both NavMesh.FindClosestEdge and (NavMesh.SamplePosition return “True” when I feel they shouldn’t be. I’ve tried making a for loop that checks in a a spiral pattern from the player but the if check is always returning true.

 public override TaskStatus OnUpdate()
 
        {
            float sprialSize = 1;
            Vector3 playerPos = target.transform.position;
            Vector3 tempPos = playerPos;
            NavMeshHit hit;
            for (int i = 0; i < 1000; i++)
            {

                Vector3 newPos = new Vector3((tempPos.x + sprialSize), tempPos.y, (tempPos.z + sprialSize));
                Debug.Log(newPos);
                Debug.Log(i);
                Debug.Log(NavMesh.GetAreaFromName(areaName));
                if (NavMesh.FindClosestEdge(newPos, out hit, NavMesh.GetAreaFromName(areaName)))
                {
                    if (NavMesh.SamplePosition(hit.position, out NavMeshHit HitIn, .1f, NavMesh.GetAreaFromName(areaName)))
                    {
                        float dist = Vector3.Distance(target.transform.position, hit.position);
                        setVector3Variable.Value = HitIn.position;
                        break;
                    }
                }
            }
               
            return base.OnUpdate();
        }

Again, a massive thank you for your help.
Nathan

That’s interesting. I didn’t know the FindClosestEdge had a max radius. I will play around on that same sample scene and see if I can reproduce what you’ve mentioned and get back to you later in the week.

1 Like

Hi Nathan,

Sorry I can’t reproduce the issue you’re talking about. In this video you can see it running up to 30 units away without any issue finding the closest edge, bouncing between edges as I move the Agent around. This is using the exact same code from above so it’s hard to say what is happening in your particular case.

You may simplify your scene to see if you can get it working, then slowly re-add scripts and GameObjects (I’d just disable everything not directly related to this, then slowly re-enable them to see where it breaks).

Here’s the Editor code so you can use it as a debugging tool to help you as well. You can make a folder called “Editor” in the “Assets” folder then put this script in that folder:

using UnityEditor;
using UnityEngine;
using UnityEngine.AI;

[CustomEditor(typeof(GoToWater))]
public class GoToWaterEditor : Editor
{
    private void OnSceneGUI()
    {
        GoToWater goToWater = (GoToWater)target;

        GUIStyle normalStyle = new GUIStyle()
        {
            normal = new GUIStyleState()
            {
                textColor = Color.black
            },
            fontSize = 24
        };
        GUIStyle errorStyle = new GUIStyle()
        {
            normal = new GUIStyleState()
            {
                textColor = Color.red
            },
            fontSize = 24
        };

        if (goToWater == null)
        {
            return;
        }

        if (NavMesh.FindClosestEdge(goToWater.Agent.transform.position, out NavMeshHit hit, NavMesh.GetAreaFromName("Water")))
        {
            Handles.DrawLine(goToWater.Agent.transform.position, hit.position);
            Handles.Label(goToWater.transform.position, $"Distance: {Vector3.Distance(goToWater.Agent.transform.position, hit.position)}", normalStyle);
        }
        else
        {
            Handles.Label(goToWater.transform.position, "Distance: UNKNOWN", errorStyle);
        }
          
    }
}
2 Likes