-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAStarPathFindService.cs
109 lines (90 loc) · 3.2 KB
/
AStarPathFindService.cs
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
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AStar
{
public class AStarPathFindService : IPathFindService
{
private readonly IGraphNeighborsService _neighborsService;
public AStarPathFindService(IGraphNeighborsService neighborsService)
{
_neighborsService = neighborsService;
}
/// <summary>
/// Found optimal path on graph using A* algorithm
/// </summary>
/// <returns> path object or null, if path not found </returns>
public GraphPath Find(IGraph graph, PathFindingOptions options)
{
if (graph == null)
{
throw new ArgumentNullException(nameof(graph));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var neighbors = new List<Vector2Int>(8);
var frontier = new PriorityQueue<Vector2Int>();
frontier.Add(0, options.End);
var cameFrom = new Dictionary<Vector2Int, Vector2Int>();
var costsFar = new Dictionary<Vector2Int, float>()
{
[options.End] = 0
};
while (frontier.Count > 0)
{
if (NextVariant())
{
break;
}
}
if (!costsFar.ContainsKey(options.Start))
{
return null;
}
var result = new GraphPath();
result.Path = new List<Vector2Int>();
var reverseNode = options.Start;
while (reverseNode != null)
{
result.Path.Add(reverseNode);
if (!cameFrom.ContainsKey(reverseNode))
{
break;
}
reverseNode = cameFrom[reverseNode];
}
return result;
bool NextVariant()
{
var current = frontier.Peek();
frontier.RemoveMin();
if (current == options.Start)
{
return true;
}
_neighborsService.GetNeighbors(graph, current, neighbors);
foreach (var neighbor in neighbors)
{
var newCost = costsFar[current] + graph.GetTransition(current, neighbor);
if (!costsFar.ContainsKey(neighbor) || newCost < costsFar[neighbor])
{
costsFar[neighbor] = newCost;
var priority = (newCost + Heuristic(options.Start, neighbor));
frontier.Add(priority, neighbor);
cameFrom[neighbor] = current;
}
}
return false;
}
}
/// <summary>
/// Heuristic function, https://en.wikipedia.org/wiki/Chebyshev_distance
/// </summary>
private float Heuristic(Vector2Int from, Vector2Int to)
{
return Vector2Int.Distance(from, to);Math.Max(Math.Abs(from.x - to.x), Math.Abs(from.y - to.y));
}
}
}