NavmeshClamp.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. namespace Pathfinding {
  3. /// <summary>
  4. /// Attach to any GameObject and the object will be clamped to the navmesh.
  5. /// If a GameObject has this component attached, one or more graph linecasts will be carried out every frame to ensure that the object
  6. /// does not leave the navmesh area.
  7. /// It can be used with GridGraphs, but Navmesh based ones are prefered.
  8. ///
  9. /// Note: This has partly been replaced by using an RVOController along with RVONavmesh.
  10. /// It will not yield exactly the same results though, so this script is still useful in some cases.
  11. /// </summary>
  12. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_navmesh_clamp.php")]
  13. public class NavmeshClamp : MonoBehaviour {
  14. GraphNode prevNode;
  15. Vector3 prevPos;
  16. // Update is called once per frame
  17. void LateUpdate () {
  18. if (prevNode == null) {
  19. var nninfo = AstarPath.active.GetNearest(transform.position);
  20. prevNode = nninfo.node;
  21. prevPos = transform.position;
  22. }
  23. if (prevNode == null) {
  24. return;
  25. }
  26. if (prevNode != null) {
  27. var graph = AstarData.GetGraph(prevNode) as IRaycastableGraph;
  28. if (graph != null) {
  29. GraphHitInfo hit;
  30. if (graph.Linecast(prevPos, transform.position, out hit)) {
  31. hit.point.y = transform.position.y;
  32. Vector3 closest = VectorMath.ClosestPointOnLine(hit.tangentOrigin, hit.tangentOrigin+hit.tangent, transform.position);
  33. Vector3 ohit = hit.point;
  34. ohit = ohit + Vector3.ClampMagnitude((Vector3)hit.node.position-ohit, 0.008f);
  35. if (graph.Linecast(ohit, closest, out hit)) {
  36. hit.point.y = transform.position.y;
  37. transform.position = hit.point;
  38. } else {
  39. closest.y = transform.position.y;
  40. transform.position = closest;
  41. }
  42. }
  43. prevNode = hit.node;
  44. }
  45. }
  46. prevPos = transform.position;
  47. }
  48. }
  49. }