Example #1
0
        private void AddTileCell(Vector2 tilePos)
        {
            var astarPos = tilePos + Vector2.Up;

            _astar.AddPoint(_astarId, astarPos, 1f);
            var astarCell = new AstarCell(astarPos, _astarId);

            _astarCells.Add(astarCell);
            _positionToCell[astarCell.Position] = astarCell;

            // connect the point to the left
            if (_astarId > 0 && _astar.GetPointPosition(_astarId - 1) == astarPos + Vector2.Left)
            {
                _astar.ConnectPoints(_astarId - 1, _astarId, true);
            }

            var isRightCorner = _tileMap.GetCellv(tilePos + Vector2.Right) == TileMap.InvalidCell;
            var isLeftCorner  = _tileMap.GetCellv(tilePos + Vector2.Left) == TileMap.InvalidCell;

            if (isRightCorner || isLeftCorner)
            {
                var cornerCell = new AstarCornerCell(astarPos, isLeftCorner);
                _astarCornerCells.Add(cornerCell);
            }

            _astarId++;
        }
Example #2
0
    public List <Vector2Int> GetPathTo(Vector2Int destination)
    {
        List <AstarCell> openList  = new List <AstarCell>();
        List <AstarCell> closeList = new List <AstarCell>();

        Vector2Int startCoord = Coordinates;
        AstarCell  current    = new AstarCell();

        current.pos       = startCoord;
        current.cost      = 0;
        current.heuristic = 0f;
        current.prev      = null;
        openList.Add(current);

        bool found = false;

        while (openList.Count > 0 && found == false)
        {
            current = openList.Find(min => min.TotalCost() == openList.Min(x => x.TotalCost()));
            closeList.Add(current);
            openList.Remove(current);

            if (current.pos == destination)
            {
                found = true;
                break;
            }

            foreach (GameCell n in board.GetNeihbours(current.pos))
            {
                if (openList.Find(x => x.pos == n.coordinates) == null &&
                    closeList.Find(x => x.pos == n.coordinates) == null &&
                    !n.IsWall)
                {
                    AstarCell neighbour = new AstarCell();
                    neighbour.pos       = n.coordinates;
                    neighbour.cost      = current.cost + 1;
                    neighbour.heuristic = Vector2.Distance(n.transform.position, board.GetCell(destination).transform.position);
                    neighbour.prev      = current;
                    openList.Add(neighbour);
                }
            }
        }

        if (found)
        {
            List <Vector2Int> path = new List <Vector2Int>();
            for (AstarCell cell = closeList.Last(); cell.pos != startCoord; cell = cell.prev)
            {
                path.Add(cell.pos);
            }
            path.Reverse();
            return(path);
        }
        else
        {
            return(null);
        }
    }