1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
| using System; using System.Collections.Generic; using JKFrame; using Unity.VisualScripting; using UnityEngine; using UnityEngine.PlayerLoop; using Random = UnityEngine.Random;
namespace AStar { public class AStarManager : SingletonMono<AStarManager> { private int _mapW; private int _mapH;
private AStarNode[,] _nodes;
private List<AStarNode> _openList;
private List<AStarNode> _closeList;
public void InitMapInfo(int w, int h) { _mapW = w; _mapH = h; _nodes = new AStarNode[w, h]; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { var node = new AStarNode(i, j, Random.Range(0, 100) < 20 ? NodeType.Stop : NodeType.Walk); _nodes[i, j] = node; } } }
public List<AStarNode> FindPath(Vector2 startPos, Vector3 endPos) {
if (startPos.x < 0 || startPos.x >= _mapW || startPos.y < 0 || startPos.y >= _mapH || endPos.x < 0 || endPos.x >= _mapW || endPos.y < 0 || endPos.y >= _mapH) return null;
AStarNode start = _nodes[(int)startPos.x, (int)startPos.y]; AStarNode end = _nodes[(int)endPos.x, (int)endPos.y];
if (start.Type == NodeType.Stop|| end.Type == NodeType.Stop) return null;
_closeList.Clear(); _openList.Clear(); start.Father = null; start.F = 0; start.G = 0; start.H = 0; _closeList.Add(start);
while (true) { FindNearlyNodeToOpenList(start.X-1,start.Y-1,1.4f,start,end); FindNearlyNodeToOpenList(start.X-1,start.Y,1f,start,end); FindNearlyNodeToOpenList(start.X-1,start.Y+1,1.4f,start,end); FindNearlyNodeToOpenList(start.X+1,start.Y-1,1.4f,start,end); FindNearlyNodeToOpenList(start.X+1,start.Y,1f,start,end); FindNearlyNodeToOpenList(start.X+1,start.Y+1,1.4f,start,end); FindNearlyNodeToOpenList(start.X,start.Y+1,1f,start,end); FindNearlyNodeToOpenList(start.X,start.Y-1,1f,start,end); if (_openList.Count == 0) { return null; } _openList.Sort(SortOpenList);
_closeList.Add(_openList[0]); start = _openList[0]; _openList.RemoveAt(0); if (start == end) { List<AStarNode> path = new List<AStarNode>(); path.Add(end); while (end.Father != null) { path.Add(end.Father); end = end.Father; } path.Reverse(); return path; } } }
private int SortOpenList(AStarNode a, AStarNode b) { if (a.F>b.F) { return 1; } else { return -1; } }
private void FindNearlyNodeToOpenList(int x, int y,float g,AStarNode father,AStarNode end) { if (x < 0 || x >= _mapW || y < 0 || y >= _mapH) return; var node = _nodes[x, y]; if (node == null || node.Type == NodeType.Stop|| _openList.Contains(node)|| _closeList.Contains(node)) return;
node.Father = father; node.G = father.G + g; node.H = Mathf.Abs(end.X - node.X) + Mathf.Abs(end.Y - node.Y);
} } }
|