Potential alternative to save some calculation

Instead of the GetPathLength solution presented in the video, I found a potential alternative that might have the benefit of eliminating some unnecessary calculations.

I created a method named PathIsTooLong instead:

      private bool PathIsTooLong(NavMeshPath path)
      {
         // start calculating path length from my current position
         Vector3 currentWaypoint = transform.position;
         float length = 0;
         
         // cycle through path corners
         foreach (Vector3 nextCorner in path.corners)
         {
            // add the distance from my current position to the next corner
            length += Vector3.Distance(currentWaypoint, nextCorner);

            // if length is longer than the max path length, don't bother caclculating further
            if (length > maxPathLength) return true;
            
            // otherwise, update my current waypoint to the corner
            currentWaypoint = nextCorner;
         }
         // if I've made it this far, the path is NOT too long
         return false;
      }

Then, back in the calling method RaycastNavMesh, my final check is simply this:

         // if complete path to target is too long, return false
         if (PathIsTooLong(path)) return false;

This approach bails before subsequent corner-to-corner distance calculations if the path length is already longer than the specified max.

Please let me know if anyone sees potential problems with this alternative.

2 Likes

Given how close up our camera view is to the player, there is probably not that much of an optimization to bother (unless you’ve got some zig-zag lining, like they do for queuing up at an airport or other waiting line). Apart from that it’s a good approach. I like it.

Privacy & Terms