TargetMover.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using UnityEngine;
  2. using System.Linq;
  3. namespace Pathfinding {
  4. /// <summary>
  5. /// Moves the target in example scenes.
  6. /// This is a simple script which has the sole purpose
  7. /// of moving the target point of agents in the example
  8. /// scenes for the A* Pathfinding Project.
  9. ///
  10. /// It is not meant to be pretty, but it does the job.
  11. /// </summary>
  12. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_target_mover.php")]
  13. public class TargetMover : MonoBehaviour {
  14. /// <summary>Mask for the raycast placement</summary>
  15. public LayerMask mask;
  16. public Transform target;
  17. IAstarAI[] ais;
  18. /// <summary>Determines if the target position should be updated every frame or only on double-click</summary>
  19. public bool onlyOnDoubleClick;
  20. public bool use2D;
  21. Camera cam;
  22. public void Start () {
  23. //Cache the Main Camera
  24. cam = Camera.main;
  25. // Slightly inefficient way of finding all AIs, but this is just an example script, so it doesn't matter much.
  26. // FindObjectsOfType does not support interfaces unfortunately.
  27. ais = FindObjectsOfType<MonoBehaviour>().OfType<IAstarAI>().ToArray();
  28. useGUILayout = false;
  29. }
  30. public void OnGUI () {
  31. if (onlyOnDoubleClick && cam != null && Event.current.type == EventType.MouseDown && Event.current.clickCount == 2) {
  32. UpdateTargetPosition();
  33. }
  34. }
  35. /// <summary>Update is called once per frame</summary>
  36. void Update () {
  37. if (!onlyOnDoubleClick && cam != null) {
  38. UpdateTargetPosition();
  39. }
  40. }
  41. public void UpdateTargetPosition () {
  42. Vector3 newPosition = Vector3.zero;
  43. bool positionFound = false;
  44. if (use2D) {
  45. newPosition = cam.ScreenToWorldPoint(Input.mousePosition);
  46. newPosition.z = 0;
  47. positionFound = true;
  48. } else {
  49. // Fire a ray through the scene at the mouse position and place the target where it hits
  50. RaycastHit hit;
  51. if (Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity, mask)) {
  52. newPosition = hit.point;
  53. positionFound = true;
  54. }
  55. }
  56. if (positionFound && newPosition != target.position) {
  57. target.position = newPosition;
  58. if (onlyOnDoubleClick) {
  59. for (int i = 0; i < ais.Length; i++) {
  60. if (ais[i] != null) ais[i].SearchPath();
  61. }
  62. }
  63. }
  64. }
  65. }
  66. }