Example image: http://ericsartor.ca/Untitled2.gif
I'm making a game based on a grid system. For the battle system, I'm trying to figure out if a shot is blocked by checking all the squares in it's path to see if they are considered "obstacles". I'd need to be able to provide a start and end x,y coordinate, then loop through all the squares that the line between those points would pass through, as in the image. The formula would need to return x,y coordinates for each square in the path. I could iterate over it multiple times if necessary. I've been trying really hard to figure it out on my own, but I can't identify a clear pattern or consistency that I could use to make a formula. Could someone help? Thanks :)
I believe I have a solution for you. Suppose the grid is defined by all lines parallel to the $y$-axis through the points $\{x_k = a + k\Delta x\,:\,k \in \mathbb{Z}\}$ and all lines parallel to the $x$-axis through the points $\{y_j = b + j\Delta y\,:\,j\in\mathbb{Z}\}$. Further suppose the line extends from $(x_s,y_s)$ to $(x_e,y_e)$. The following pseudocode outlines the algorithm. At its conclusion the array $P$ contains a list of index pairs $(k,j)$ that index the bottom left corner of the rectangle with vertices $(x_k,y_j)$, $(x_k,y_j + \Delta y)$, $(x_k + \Delta x, y_j)$, $(x_k+\Delta x,y_j + \Delta y)$ that contains a portion of the line.
This algorithm may have to be tweaked depending on how you want to handle edge cases such as when the line passes through grid points.