I am working on a text based (console) WW2 strategy game, set on a 2d square grid map. I want a method to calculate line of sight from one tile on the map to another. I've used this Java example to base my code off, this is what I've written:
public function plotLine($x0, $y0, $x1, $y1, $size)
{
$arr = $this->getEmptyMap($size);
$xDist = abs($x1 - $x0);
$yDist = -abs($y1 - $y0);
if($x0 < $x1) {
$xStep = 1;
} else {
$xStep = -1;
}
if($y0 < $y1) {
$yStep = 1;
} else {
$yStep = -1;
}
$plotError = $xDist + $yDist;
$arr[$x0][$y0] = 1;
while($x0 != $x1 || $y0 != $y1) {
// if(2 * $plotError > $yDist) {
// // Horizontal step
// $plotError += $yDist;
// $x0 += $xStep;
// }
// if(2 * $plotError < $xDist) {
// // Vertical step
// $plotError += $xDist;
// $y0 += $yStep;
// }
if(2 * $plotError - $yDist > $xDist - 2 * $plotError) {
// Horizontal step
$plotError += $yDist;
$x0 += $xStep;
} else {
// Vertical step
$plotError += $xDist;
$y0 += $yStep;
}
$arr[$x0][$y0] = 1;
}
$this->line = $arr;
}
Note: getEmptyMap just fills a multidimensional array with 0's.
Testresult using (0, 0, 4, 4, 4) as input:
1100
0110
0011
0001
I've tried to ways of mapping the line: one is the normal implementation that Franz D. used (currently commented out in my example above), the other is the modified implementation that Franz D. showed. Neither is giving me the result I'm looking for; a kind of "anti-aliasing". When a solder would look from 0,0 at 2,2 and there would be buildings at 1,2 and 2,1, whatever is at 2,2 should be blocked from sight. The commented out implementation would completely ignore the buildings, the modification does "hit" 2,1 but not 1,2. How would I adjust my code to "hit" both underneath the line and above the line?