Skip to content

Instantly share code, notes, and snippets.

@joehonton
Last active June 11, 2022 01:58
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 joehonton/9f69e4b34de21df5818cb1d240023b68 to your computer and use it in GitHub Desktop.
Save joehonton/9f69e4b34de21df5818cb1d240023b68 to your computer and use it in GitHub Desktop.
function isInsideClippedPolygon(polygon, mouseX, mouseY) {
let c = false;
// make sure there are at least 3 visible nodes
var countv = 0;
for (let k=0; k < polygon.length && countv < 3; k++) {
if (polygon[k].visible == true)
countv++;
}
if (countv < 3)
return false;
// get the first visible node
let firstv = null;
for (let k=0; k < polygon.length; k++) {
if (polygon[k].visible == true) {
firstv = k;
break;
}
}
// raycast most-recent-visible-node -> next-visible-node
const mrv = firstv;
for (let i=mrv+1; i < polygon.length; i++) {
if (polygon[i].visible == false)
continue;
let j = mrv;
const ix = polygon[i].x;
const iy = polygon[i].y;
const jx = polygon[j].x;
const jy = polygon[j].y;
const iySide = (iy > mouseY);
const jySide = (jy > mouseY);
if (iySide != jySide) {
const intersectX = (jx-ix) * (mouseY-iy) / (jy-iy) + ix;
if (mouseX < intersectX)
c = !c;
}
mrv = i;
}
// raycast most-recent-visible-node -> first-visible-node
const ix = polygon[firstv].x;
const iy = polygon[firstv].y;
const jx = polygon[mrv].x;
const jy = polygon[mrv].y;
const iySide = (iy > mouseY);
const jySide = (jy > mouseY);
if (iySide != jySide) {
const intersectX = (jx-ix) * (mouseY-iy) / (jy-iy) + ix;
if (mouseX < intersectX)
c = !c;
}
return c;
}
@codeSourc3
Copy link

The variable firstv, c would have to be let instead of const to be reassignable.

@joehonton
Copy link
Author

Corrected firstv and c per @codeSourc3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment