Created
December 15, 2022 07:09
-
-
Save deleteman/ed90086655294408701eb1ea5b4015bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getPath(startX, startY, endX, endY) { | |
// Initialize an empty array to store the coordinates of the points on the path | |
let path = []; | |
// Use the Bresenham's line algorithm to get the coordinates of the points on the path | |
let x1 = startX, y1 = startY, x2 = endX, y2 = endY; | |
let isSteep = Math.abs(y2 - y1) > Math.abs(x2 - x1); | |
if (isSteep) { | |
[x1, y1] = [y1, x1]; | |
[x2, y2] = [y2, x2]; | |
} | |
let isReversed = false; | |
if (x1 > x2) { | |
[x1, x2] = [x2, x1]; | |
[y1, y2] = [y2, y1]; | |
isReversed = true; | |
} | |
let deltax = x2 - x1, deltay = Math.abs(y2 - y1); | |
let error = Math.floor(deltax / 2); | |
let y = y1; | |
let ystep = null; | |
if (y1 < y2) { | |
ystep = 1; | |
} else { | |
ystep = -1; | |
} | |
for (let x = x1; x <= x2; x++) { | |
if (isSteep) { | |
path.push([y, x]); | |
} else { | |
path.push([x, y]); | |
} | |
error -= deltay; | |
if (error < 0) { | |
y += ystep; | |
error += deltax; | |
} | |
} | |
// If the line is reversed, reverse the order of the points in the path | |
if (isReversed) { | |
path = path.reverse(); | |
} | |
return path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment