Nav Graph (C# / Unity)
An AI navigation graph for 2D games developed in Unity. This partial implementation was originally part of Book of Dreams, and uses Unity’s 2D Polygon Colliders to generate a corner graph for AI pathfinding.
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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
/*! \file NavGraph2D.cs \author David Knopp \details A 2D navigation graph utilizing Unity's PolygonCollider2D \copyright All content © 2014-2015 DigiPen (USA) Corporation, all rights reserved. */ using UnityEngine; using System.Collections.Generic; using Utils; [RequireComponent(typeof(PolygonCollider2D))] /*! \brief 2D navigation graph defined by a PolygonCollider2D */ public class NavGraph2D : ISingleton { // public members / properties public float nodeOffset = 0.5f; //!< Amount to offset nodes from edges //!< The polygon defining the graph public Polygon2D polygon { get { return _polys[0]; } } /** \brief Calculates the distance between two nodes \param nodeA First node \param nodeB Second node \return Distance between nodeA and nodeB */ public float Distance(int nodeA, int nodeB) { // get nodes by id GraphNode2D a = _graph.GetNode(nodeA); GraphNode2D b = _graph.GetNode(nodeB); return (a.pos - b.pos).magnitude; } /** \brief Determines if a given point is on the nav graph \param point The point to check \return Whether or not the point lies on the graph */ public bool PointOnGraph(Vector2 point) { if (_polys[0].CollidingWith(point)) { // check if point within an obstacle foreach (NavGraph2DObstacle obstacle in _obstacles) { if (obstacle.polygon.CollidingWith(point)) return false; } return true; } return false; } /** \brief Checks if there is a valid line of sight between two points \param start The first point \param end The second point \return Whether or not there is a valid line of sight */ public bool ValidLOS(Vector2 start, Vector2 end) { // check intersection between graph's polygons foreach (Polygon2D poly in _polys) { for (int i = 0; i < poly.numPoints; ++i) { int next = NextIndex(poly, i); if (RGMath.LineSegment2DInteresect(start, end, poly.points[i], poly.points[next])) return false; } } return true; } /** \brief Initializes the navigation graph */ private void Awake() { _graph = new NavGraph(); _obstacles = new List(GetComponentsInChildren()); _polys = new List(); // add mesh polygon PolygonCollider2D mesh = GetComponent(); _polys.Add(new Polygon2D(mesh)); // add obstacle polygons foreach (NavGraph2DObstacle obstacle in _obstacles) { _polys.Add(new Polygon2D(obstacle.mesh, Polygon2D.WindingOrder.CCW)); } CreateNodeGraph(); LinkNodeGraph(); } /** \brief Constructs nodes at the corners of each polygon */ private void CreateNodeGraph() { // no nodes possible if mesh is a line if (polygon.numPoints < 3) return; // remove existing nodes _graph.Clear(); int curID = 0; foreach (Polygon2D poly in _polys) { // store all interior vertices of polygon for (int i = 0; i < poly.numPoints; ++i) { // find prev and next indices int prev = PreviousIndex(poly, i); int next = NextIndex(poly, i); if (IsInteriorVertex(poly.points[i], poly.points[prev], poly.points[next])) { // push node in, away from edges Vector2 offset = GetCornerOffset(poly.points[i], poly.points[prev], poly.points[next]); // add to graph if on mesh Vector2 nodePos = poly.points[i] + offset; if (PointOnGraph(nodePos)) { int id = curID++; _graph.AddNode(new GraphNode2D(nodePos, id), id); } } } } } /** \brief Links the graph's nodes together */ private void LinkNodeGraph() { List nodes = _graph.GetNodeList(); // iterate through all nodes and link if possible for (int i = 0; i < nodes.Count; ++i) { GraphNode2D from = nodes[i]; // start at i + 1, skipping any duplicate pairs for (int j = i + 1; j < nodes.Count; ++j) { GraphNode2D to = nodes[j]; // connect nodes if line of sight is valid if (ValidLOS(from.pos, to.pos)) { float cost = Distance(from.id, to.id); _graph.AddBiDirectionalEdge(from.id, to.id, cost); } } } } /** \brief Calculates the offset position of a given point (offset away from edges) \param cur The point to calculate the offset of \param prev The previous point in the polygon \param next The next point in the polygon \return The offset of the current position */ private Vector2 GetCornerOffset(Vector2 cur, Vector2 prev, Vector2 next) { // create vectors to/from neighbor points Vector2 fromPrev = cur - prev; Vector2 fromNext = cur - next; // push node in, away from edges Vector2 avg = fromPrev.normalized + fromNext.normalized; avg.Normalize(); return (avg * nodeOffset); } /** \brief Checks if a vertex forms a concave edge on a polygon \param cur The point to check \param prev The previous point in the polygon \param next The next point in the polygon \return Whether or not the vertex is interior */ private bool IsInteriorVertex(Vector2 cur, Vector2 prev, Vector2 next) { // create vectors to/from neighbors Vector2 fromPrev = cur - prev; Vector2 toNext = next - cur; float cross = RGMath.Vector2Cross(fromPrev, toNext); return (cross > 0.0f); } /** \brief Calculates the previous index of a node \param poly The polygon used for indexing \param i The current index \return The previous index (wrapped to the end if necessary) */ private int PreviousIndex(Polygon2D poly, int i) { int prev = i - 1; // wrap index to last point if (prev < 0) prev = poly.numPoints - 1; return prev; } /** \brief Calculates the next index of a node \param poly The polygon used for indexing \param i The current index \return The next index (wrapped to the beginning if necessary) */ private int NextIndex(Polygon2D poly, int i) { // wrap index back to beginning return ((i + 1) % poly.numPoints); } // private members private NavGraph _graph; //!< Underlying node graph private List _obstacles; //!< Obstacles of the graph private List _polys; //!< All polygons that make up the graph } |