How to find nearest point on a mesh (for navigation constraint)?

Hello! I’m new to Babylon, and so far I’m finding it great to work with. That said, I need some help with the task at hand…

I have a first-person scene, and I want to constrain the camera movement. I have a prebuilt navigation mesh that I’ve loaded, and every time the camera moves, I want to find the nearest point on that mesh and snap the camera to it.

I’ve seen the RecastJSPlugin, but that doesn’t seem right for my needs (it wants to build its own navigation mesh, whereas I already have one). I’ve found getClosestFacetAtLocalCoordinates, which seems like what I’m looking for, but it just gives me the nearest facet, not an exact point within the facet.

Am I on the right track? Is there way to get an exact nearest point on the nearest facet? Or should I be going about it a different way? Thank you for any help!

Hi iangilman,

Welcome to Babylon! @Cedric, our foremost RecastJS expert and the creator of the plugin, might know a better way than this, but one thing to try might be to simply let RecastJS “recreate” your nav mesh by just providing it the nav mesh itself as the nav mesh input. If you set the parameters correctly and provide only your nav mesh itself as the ground mesh, I believe the plugin should “create” a nav mesh that’s exactly the same as the one you started with. This might be a little more compute work than is necessary, but it should make the coding work much easier by allowing you to use the result as a real nav mesh equipped with all the built-in queries – most importantly getClosestPoint(...), which I believe will do exactly what you are looking for. Hope this helps, and best of luck!

Do you not need to find the facet normal?

@syntheticmagus is right, you need to compute a navmesh with recastjs before being able to call getClosestPoint. You can also compute the navmesh offline and use it back online thanks to Create Navigation Mesh - Babylon.js Documentation

Fair enough. I’ll give that a try; thank you for the help!

In the spirit of due diligence, however, I’m also interested in pursuing what would be involved in using my prebuilt navigation mesh without RecastJS. Are there any other techniques available in Babylon for getting the closest point on a mesh?

getClosestFacetAtLocalCoordinates seems promising, but the facets aren’t granular enough to use by themselves. Is there a way to get their corner vertices so I can find the exact location within the facet?

the projected parameter is the local projection on the facet.
With the face index, you can compute the world position.

1 Like