C# How to get all the tile in a straight path in a grid based game?

Hi,

So I want to do a function that return a list of tile from a grid in a straight path (and each tile shall touch each other) from two coordinate in a grid, the start and the end tile.

I’ve seen a the Bresenham’s Line Algorithm but I just can’t understand it since all the video that I see are not explaining that well or I’m dumb.

I could do it with the A* algorithm that I already implemented, but I feel like it would not make perfect line since he just need to find the fastest path and it might be to only go on x until its at the good coordinate and the go on y. (My A* don t work with the diagonal neighbour because I don’t want the caracter to go diagonaly(I could make it diagonaly but that would not really solve my problem since I want to get all the tile in a straight and the tile shall touch each other))

the only solutions I thought could go well would be to do a ray cast all and I transform all there position into there tile linked to it, but I feel like it would use a lot of performance compare to the a simple mathmatical formula.

Thanks for the help182982-capture.png

Ok so I tried to make it that they all touch but it’s kinda complicated to accomplish but I still got this code that work perfectly :

List<Cell> validCells = new List<Cell>();

        Vector2Int currentPosition = startCell.Position;
        Vector2Int endPosition = endCell.Position;

        Vector2Int startDifference = new Vector2Int(Mathf.Abs(endPosition.x - currentPosition.x), Mathf.Abs(endPosition.y - currentPosition.y));

        int error = 0;

        Vector2Int difference = startDifference * 2;

        Vector2Int addition = new Vector2Int(1, 1);

        if (currentPosition.x > endPosition.x) addition.x = -1;
        if (currentPosition.y > endPosition.y) addition.y = -1;

        if (startDifference.x > startDifference.y)
        {
            error = startDifference.x;
            for (int i = 0; i <= startDifference.x; i++)
            {
                validCells.Add(_mapManager.GetCell(currentPosition));
                currentPosition.x += addition.x;
                error -= difference.y;
                if (error <= 0)
                {
                    currentPosition.y += addition.y;
                    error += difference.x;
                }
            }
        }
        else
        {
            error = startDifference.y;
            for (int i = 0; i <= startDifference.y; i++)
            {
                validCells.Add(_mapManager.GetCell(currentPosition));
                currentPosition.y += addition.y;
                error -= difference.x;
                if (error <= 0)
                {
                    currentPosition.x += addition.x;
                    error += difference.y;
                }
            }
        }