Skip to content

Instantly share code, notes, and snippets.

@Langerz82
Last active July 26, 2022 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Langerz82/32a9707b83bfd03dd5b041ab1f2309c6 to your computer and use it in GitHub Desktop.
Save Langerz82/32a9707b83bfd03dd5b041ab1f2309c6 to your computer and use it in GitHub Desktop.
JavaScript - Node function - isValidPath: Checks a two-dimensional array ex: [[x1,y1],[x2,y2]] for validity against a collision map.
// TODO - Grid axis is not being checked properly.
isValidPath: function (grid, path) {
// Check collision from an axis, n1 to n2, n3 is for the other axis.
var c1to2on3 = function (n1,n2,n3,axis) {
log.info("c1to2on3 - n1:"+n1+",n2:"+n2+",n3:"+n3);
var isDec = (n3 % 1 == 0);
var n1f = Math.floor(n1), n2c = Math.ceil(n2);
var i1 = Math.min(n1f,n2c), i2 = Math.max(n1f,n2c);
if (n1f != n2c) {
var n3f=Math.floor(n3), n3c=Math.ceil(n3);
if (axis == "x") {
for (var i=i1; i < i2; i++) {
if (isDec) {
if (grid[n3][i]) {
return false;
}
}
else {
if (grid[n3f][i] || grid[n3c][i]) {
return false;
}
}
}
} else {
for (var i=i1; i < i2; i++) {
if (isDec) {
if (grid[i][n3]) {
return false;
}
}
else {
if (grid[i][n3f] || grid[i][n3c]) {
return false;
}
}
}
}
}
return true;
}
var xf = function (x1,x2,y) {
return c1to2on3(x1,x2,y,"x");
}
var yf = function (y1,y2,x) {
return c1to2on3(y1,y2,x,"y");
}
var path2 = [];
for (var i = 0; i < path.length; i++)
path2[i] = path[i].slice();
var pCoord;
var ts = G_TILESIZE;
for (var coord of path2) {
coord[0] /= ts;
coord[1] /= ts;
}
for (var coord of path2) {
if (!pCoord) pCoord = coord;
if (pCoord) {
if (Math.abs(coord[0] - pCoord[0]) > 0) {
if (!xf(pCoord[0], coord[0], coord[1]))
return false;
}
if (Math.abs(coord[1] - pCoord[1]) > 0) {
if (!yf(pCoord[1], coord[1], coord[0]))
return false;
}
}
}
return true;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment