Limit movement to area contained in grid graph

My project has an “exploration mode” which works in real time (no pathfinding, uses a regular character controller limited by collision), and then a “combat mode” in which the grid nodes are displayed and is turn-based.

I would like to limit the player movement during “exploration mode” to the area that is contained within the grid nodes; i.e, I don’t want it to be possible to fall off cliffs, or to squeeze into areas that have no nodes. I think a navmesh is the obvious tool to do this, but since I already have a grid graph (and I need it for the tactical combat), is there an easy way to check on update if the player position is within the “surface” covered by nodes? it would be exactly the surface displayed on the editor when you scan.

PS: I have the pro version, so maybe one of the advanced types of graphs could be the solution, but the grid graph is exactly what I need for combat so I’m using it for now.

Hi

You can query for the closest point on the graph and snap the picked point to that:

var info = AstarPath.active.GetNearest(somePosition, NNConstraint.Default);
if (info.node == null) Debug.LogError("No valid point on a graph could be found");
var closestPointOnGraph = info.position;

So if you each frame query for the closest point on the graph to the player’s position and then move the player there it should behave as if it is snapped to the navmesh. This will work on both grid graphs and navmesh/recast graphs.

A slightly more advanced approach would be to use the Linecast methods (that exist on both grid graphs and navmesh/recast graphs). You could fire a linecast from the player’s position to where the player wants to move and check if any obstacles were hit.
This avoids one edge case in which the player would move a significant distance in a single frame (perhaps the FPS was really low) which ended up causing the player to be closer to some unintended part of the graph (perhaps on the other side of a wall). However in pretty much all cases the simpler GetNearest method used above will work well enough.

See https://arongranberg.com/astar/docs/class_astar_path.php#aae44d9d57ed269658eef4dddae3af43e
See https://arongranberg.com/astar/docs/class_pathfinding_1_1_grid_graph.php#a812452a7bf8ab63400efc7ab0ebdd63c