- Home /
Check if object without NavMeshAgent component is under navmesh
So, the player object is not using the navmesh, it is controlled by a virtual joystick altough I have a map baked for the mobs. I am trying to teleport the player randomly inside the navmesh, so he does not go outside the map. How can I check if his position is under navmesh if it does not have a NavMeshAgent component? Or is there a better way to prevent him from teleporting outside the "box"?
Answer by mischkom · Aug 18, 2021 at 01:17 PM
Do the objects (walls etc.) of this labyrinth have Colliders ? then you could teleport your player to a location inside of it after checking with Physics.CheckSphere if theres enough space for your character model at that point. Besides that there is NavMesh.FindClosestEdge. "Locate the closest NavMesh edge from a point on the NavMesh."
if (NavMesh.FindClosestEdge(transform.position, out hit, NavMesh.AllAreas))
now either this returns true/false depending on if you are on the navmesh or not (i am not sure myself how this woudl behave) or if its able to find an edge without being on the mesh, you could teleport your character to that edge and let him spawn closest to where he would have spawned if there was a mesh.
FindCLosestEdge() is exactly what I was looking for, I did not know this exists, thank you! Now the teleportation works like a charm:
public void usePowerUp() {
safePosition = tpPosition = transform.localPosition;
randomNr = Random.Range($$anonymous$$Radius, maxRadius);
if(Random.value < 0.5) tpPosition.x += randomNr;
else tpPosition.x -= randomNr;
if(Random.value < 0.5) tpPosition.z += randomNr;
else tpPosition.z -= randomNr;
transform.localPosition = tpPosition;
NavMeshHit hit;
if (!NavMesh.FindClosestEdge(transform.position, out hit, NavMesh.AllAreas)){
transform.localPosition = safePosition;
Debug.Log("retrying... " + safePosition);
usePowerUp();
}
}
Your answer
Follow this Question
Related Questions
is it possible to use navmesh on flying character and target ? 0 Answers
How to speed up built-in Unity pathfinding using navMesh? 1 Answer
NavMesh Agent Obstacle Avoidance Ignore 1 Answer
How to add variables to Components (Nav Mesh Agent)? 0 Answers
Modify NavMeshPath for Tactical FPS (slicing the pie/sweeping maneuver) 0 Answers