DDA Line Algorithm Improvement
Fixed! See here for more info: https://gamedev.stackexchange.com/q/81267/63053
by Chris Dennis
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<canvas id="canvas"></canvas>
<pre id="infos"></pre>
</body>
</html>
JavaScript
function intersect(start, end) {
//Grid cells are 1.0 X 1.0.
let x = Math.floor(start.x);
let y = Math.floor(start.y);
let diffX = end.x - start.x;
let diffY = end.y - start.y;
let stepX = Math.sign(diffX);
let stepY = Math.sign(diffY);
//Ray/Slope related maths.
//Straight distance to the first vertical grid boundary.
let xOffset = end.x > start.x ?
(Math.ceil(start.x) - start.x) :
(start.x - Math.floor(start.x));
//Straight distance to the first horizontal grid boundary.
let yOffset = end.y > start.y ?
(Math.ceil(start.y) - start.y) :
(start.y - Math.floor(start.y));
//Angle of ray/slope.
let angle = Math.atan2(-diffY, diffX);
//NOTE: These can be divide by 0's, but JS just yields Infinity! :)
//How far to move along the ray to cross the first vertical grid cell boundary.
let tMaxX = xOffset / Math.cos(angle);
//How far to move along the ray to cross the first horizontal grid cell boundary.
let tMaxY = yOffset / Math.sin(angle);
//How far to move along the ray to move horizontally 1 grid cell.
let tDeltaX = 1.0 / Math.cos(angle);
//How far to move along the ray to move vertically 1 grid cell.
let tDeltaY = 1.0 / Math.sin(angle);
//Travel one grid cell at a time.
let manhattanDistance = Math.abs(Math.floor(end.x) - Math.floor(start.x)) +
Math.abs(Math.floor(end.y) - Math.floor(start.y));
for (let t = 0; t <= manhattanDistance; ++t) {
drawSquare(x, y);
//Only move in either X or Y coordinates, not both.
if (Math.abs(tMaxX) < Math.abs(tMaxY)) {
tMaxX += tDeltaX;
x += stepX;
} else {
tMaxY += tDeltaY;
y += stepY;
}
}
infos.innerHTML = "";
infos.innerHTML += "diffX: " + diffX + "<br/>diffY: " + diffY + "<br/>";
infos.innerHTML += "stepX: " + stepX + "<br/>stepY: " + stepY + "<br/>";
infos.innerHTML += "xOffset: " + xOffset + "<br/>yOffset: " + yOffset + "<br/>";
infos.innerHTML += "tMaxX: " + tMaxX + "<br/>tMaxY: " +...