Esempio n. 1
0
        public IEnumerable <PathfindCell> GetGlobalPath(Vector2 globalFrom, Vector2 globalTo)
        {
            var fromId = _astar.GetClosestPoint(globalFrom / TILE_SIZE);
            var toId   = _astar.GetClosestPoint(globalTo / TILE_SIZE);
            var idPath = _astar.GetIdPath(fromId, toId);

            var offset = new Vector2(TILE_SIZE / 2f, TILE_SIZE);

            return(idPath.Select(x => new PathfindCell(x, _astar.GetPointWeightScale(x), _astar.GetPointPosition(x) * TILE_SIZE + offset)));
        }
Esempio n. 2
0
    //Calculates the Minimum Spanning Tree (MST) for given points and returns an `AStar2D` graph using Prim's algorithm.
    // https://en.wikipedia.org/wiki/Prim%27s_algorithm
    // https://en.wikipedia.org/wiki/Minimum_spanning_tree
    public static AStar2D MST(List <Vector2> pointsList)
    {
        var result = new AStar2D();

        var firstPoint = pointsList.LastOrDefault();

        //Start from an arbitrary point in the list of points
        result.AddPoint(result.GetAvailablePointId(), firstPoint);
        pointsList.Remove(firstPoint);

        //Loop through all points, erasing them as we connect them.
        while (pointsList.Any())
        {
            var currentPosition = Vector2.Zero;
            var minPosition     = Vector2.Zero;
            var minDistance     = float.PositiveInfinity;

            foreach (int point1Id in result.GetPoints())
            {
                //Compare each point added to the Astar2D graph to each remaining point to find the closest one
                var point1Position = result.GetPointPosition(point1Id);
                foreach (var point2Position in pointsList)
                {
                    var distance = point1Position.DistanceTo(point2Position);
                    if (minDistance > distance)
                    {
                        //We use the variables to store the coordinates of the closest point.
                        //We have to loop over all points to ensure it's the closest.
                        currentPosition = point1Position;
                        minPosition     = point2Position;
                        minDistance     = distance;
                    }
                }
            }

            //Connect the point closest to the "current position" with our new point
            var pointId = result.GetAvailablePointId();
            result.AddPoint(pointId, minPosition);
            result.ConnectPoints(result.GetClosestPoint(currentPosition), pointId);
            pointsList.Remove(minPosition);
        }

        return(result);
    }