예제 #1
0
        public int DistanceFromTo(HexPathNode a, HexPathNode b)
        {
            int dX = Mathf.Abs(a.Address.X - b.Address.X);
            int dY = Mathf.Abs(a.Address.Y - b.Address.Y);

            return(10 * (dX > dY ? dX : dY));
        }
예제 #2
0
        public List <HexPathNode> GetAdjacentPathNodes(HexPathNode pOrigin)
        {
            List <HexPathNode> neighbors = new List <HexPathNode>();

            foreach (Vector2Int i in NeighborIndices)
            {
                if (!HexMap.Instance.Tiles.ContainsKey(i + pOrigin.Address))
                {
                    continue;
                }

                neighbors.Add(HexMap.Instance.Tiles[i + pOrigin.Address].Data.PathNode);
            }

            return(neighbors);
        }
예제 #3
0
        public List <HexPathNode> GetPathFromTo(HexPathNode pStart, HexPathNode pEnd)
        {
            List <HexPathNode> openSet   = new List <HexPathNode>();
            List <HexPathNode> closedSet = new List <HexPathNode>();

            openSet.Add(pStart);

            while (openSet.Count > 0)
            {
                HexPathNode current = openSet[0];
                for (int i = 1; i < openSet.Count; i++)
                {
                    if (openSet[i].F < current.F || (openSet[i].F == current.F && openSet[i].H < current.H))
                    {
                        current = openSet[i];
                    }
                }

                openSet.Remove(current);
                closedSet.Add(current);

                // Found a path
                if (current == pEnd)
                {
                    List <HexPathNode> path = new List <HexPathNode>();

                    HexPathNode c = pEnd;
                    while (c != pStart)
                    {
                        path.Add(c);
                        c = current.Parent;
                    }

                    path.Reverse();

                    return(path);
                }

                foreach (HexPathNode n in GetAdjacentPathNodes(current))
                {
                    if (closedSet.Contains(n))
                    {
                        continue;
                    }

                    int costToNeighbor = current.G + DistanceFromTo(current, n) + n.BaseCost;
                    if (costToNeighbor < n.G || !openSet.Contains(n))
                    {
                        n.G = costToNeighbor;
                        n.H = DistanceFromTo(n, pEnd);

                        n.Parent = current;

                        if (!openSet.Contains(n))
                        {
                            openSet.Add(n);
                        }
                        n.Tile.HexRenderer.color = new Color(1, 1, 0);
                    }
                }
            }

            // Failed to find a path
            return(new List <HexPathNode>());
        }