xxxxxxxxxx
63
let points;
function setup() {
createCanvas(1280, 720);
points = [
createVector(0, -300),
createVector(300, 0),
createVector(-100, 300),
createVector(0, 0),
createVector(-100, 0),
createVector(-300, -100)
];
}
function draw() {
background(0);
push();
translate(width/2, height/2);
stroke(255);
strokeWeight(2);
noFill();
let pt = pointPolygonCollision(mouseX - width / 2, mouseY - height / 2, points);
beginShape();
for (let i = 0; i < points.length; i++) {
vertex(points[i].x, points[i].y);
}
endShape(CLOSE);
if (pt != null) {
stroke(255, 0, 0);
strokeWeight(10);
point(pt.x, pt.y);
}
pop();
}
function pointPolygonCollision(px, py, points) {
let num = 0;
let closestPt = createVector();
let closestDSq = Infinity;
for (let i = 0; i < points.length; i++) {
let x1 = points[i].x;
let y1 = points[i].y;
let x2 = points[(i + 1) % points.length].x;
let y2 = points[(i + 1) % points.length].y;
if (y1 > y2) {
[x1, y1, x2, y2] = [x2, y2, x1, y1];
}
let grad = (y2 - y1) / (x2 - x1);
let nx = (1/grad * px + grad * x1 + py - y1) / (1/grad + grad);
let ny = grad * (nx - x1) + y1;
let dSq = (nx - px) * (nx - px) + (ny - py) * (ny - py);
if (dSq < closestDSq) {
closestDSq = dSq;
closestPt = createVector(nx, ny);
}
if (y1 == y2) continue;
let xl = (py - y1) / (y2 - y1) * (x2 - x1) + x1;
if (y1 < py && py < y2 && xl > px) num++;
}
if (num % 2 == 0) return null;
else return closestPt;
}