Point-and-click Raycast with user-defined higher-cost Navigation Areas
Rather than indicating a desired destination by clicking an object or tile, we can use Unity's built-in Physics.Raycast(...)
method to identify which Vector3 (x,y,z) position relates to the object surface in the game.
This involves translating from the 2D (x,y) screen position to an imagined 3D "ray" from the user's point of view, through the screen, into the game world, and identifying which object (polygon) it hits first.
This recipe uses Physics.Raycast
to set the position of the location clicked on as the new destination for a NavMeshAgent
controller object. The actual route followed can be influenced by defining Navigation Mesh Areas
of different costs. For example, walking through mud or swimming through water can have a higher cost, since they would take longer, so the AI NavMeshAgent
can calculate the lowest-cost route, which may not be the shortest distance route in the scene:

Getting ready
This recipe adds to the...