Last active
June 17, 2021 15:26
-
-
Save dmoa/4b8059d1c63ebac1a266443a21291e3b to your computer and use it in GitHub Desktop.
Polygon + Point Collision Detection
This file contains 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
let polygon = [ | |
[200, 100], [400, 130], [350, 300], [250, 300] | |
]; | |
function setup() { | |
createCanvas(800, 800); | |
} | |
function draw() { | |
background(0); | |
let collision = false; | |
for (let i = 0; i < polygon.length; i++) { | |
let x1 = polygon[i][0]; | |
let y1 = polygon[i][1]; | |
let x2 = polygon[(i + 1) % polygon.length][0]; | |
let y2 = polygon[(i + 1) % polygon.length][1]; | |
if (y1 > mouseY != y2 > mouseY && mouseX < (x2 - x1) * (mouseY - y1) / (y2 - y1) + x1 ) { | |
collision = ! collision; | |
} | |
} | |
//console.log(collision); | |
//console.log(mouseX, mouseY); | |
if (collision) { | |
stroke(244, 122, 158); | |
} | |
else { | |
stroke(255, 255, 255); | |
} | |
for (let i = 0; i < polygon.length; i++) { | |
line(polygon[i][0], polygon[i][1], polygon[(i+1) % polygon.length][0], polygon[(i+1) % polygon.length][1]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment