Guest User

Untitled

a guest
Mar 23rd, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using UnityEditor;
  6.  
  7. public class PathFinder : MonoBehaviour {
  8.  
  9. public List<PathFinderNode> nodes = new List<PathFinderNode>();
  10.  
  11. [ContextMenu("gather nodes")]
  12. protected void gather_nodes() {
  13. nodes.Clear();
  14.  
  15. GameObject[] all = GameObject.FindGameObjectsWithTag("pf_node");
  16. for (int i = 0; i < all.Length; i++)
  17. {
  18. addNode(all[i].transform);
  19. }
  20.  
  21. List<PathFinderNode> links = new List<PathFinderNode>();
  22.  
  23. for (int i = 0; i < nodes.Count; i++)
  24. {
  25. links.Clear();
  26. for (int j = 0; j < nodes.Count; j++)
  27. {
  28. if (i == j) continue; // skip itself
  29. if (checkNodeLink(nodes[i], nodes[j])) links.Add(nodes[j]);
  30. }
  31.  
  32. nodes[i].links = links.ToArray();
  33. }
  34. }
  35.  
  36. protected PathFinderNode addNode(Transform nodeTr) {
  37. for (int i = 0; i < nodes.Count; i++)
  38. {
  39. if (nodes[i].tr == nodeTr) return nodes[i];
  40. }
  41. PathFinderNode node = new PathFinderNode();
  42. node.tr = nodeTr;
  43. nodes.Add(node);
  44. return node;
  45. }
  46.  
  47. bool checkNodeLink(PathFinderNode nodeA, PathFinderNode nodeB) {
  48. if(nodeA == nodeB) {
  49. Debug.LogError("same ?");
  50. return false;
  51. }
  52.  
  53. Vector3 dir = nodeB.tr.position - nodeA.tr.position;
  54. RaycastHit[] hits = Physics.RaycastAll(nodeA.tr.position, dir.normalized, dir.magnitude);
  55.  
  56. if(hits.Length <= 0) {
  57. Debug.DrawLine(nodeA.tr.position, nodeB.tr.position, Color.green, 1f);
  58. return true;
  59. }
  60.  
  61. for (int i = 0; i < hits.Length; i++)
  62. {
  63. Debug.DrawLine(nodeA.tr.position, hits[i].point, Color.red, 1f);
  64. }
  65.  
  66. return false;
  67. }
  68.  
  69. void OnDrawGizmos() {
  70. for (int i = 0; i < nodes.Count; i++)
  71. {
  72. Gizmos.DrawCube(nodes[i].tr.position, Vector3.one * 0.1f);
  73. string ct = "";
  74. for (int j = 0; j < nodes[i].links.Length; j++)
  75. {
  76. Gizmos.DrawLine(nodes[i].tr.position, nodes[i].links[j].tr.position);
  77. ct += "\n - " + nodes[i].links[j].tr.name;
  78. }
  79.  
  80. Handles.Label(nodes[i].tr.position + Vector3.up * 0.2f, ">"+nodes[i].tr.name);
  81. Handles.Label(nodes[i].tr.position, ct);
  82. }
  83. }
  84. }
  85.  
  86. [Serializable]
  87. public class PathFinderNode {
  88. public Transform tr;
  89. public PathFinderNode[] links;
  90. }
Add Comment
Please, Sign In to add comment