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 will use Physics.Raycast
to set the position of the location that’s clicked on as the new destination for a NavMeshAgent controller object. The actual route that’s 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...