const hexagon = [
new p5.Vector(50, 0),
new p5.Vector(25, 43.3),
new p5.Vector(-25, 43.3),
new p5.Vector(-50, 0),
new p5.Vector(-25, -43.3),
new p5.Vector(25, -43.3)
];
let shapes = [
{ x: 80, y: 80, color: [255, 0, 0, 100], points: hexagon },
{ x: 200, y: 200, color: [0, 255, 0, 100], points: hexagon }
];
let draggingIx;
let draggingOffset;
function setup() {
createCanvas(300, 300);
}
function draw() {
background(255);
for (let shape of shapes) {
push();
translate(shape.x, shape.y);
fill(...shape.color);
beginShape();
for (let pt of shape.points) {
vertex(pt.x, pt.y);
}
endShape(CLOSE);
pop();
}
}
function mousePressed() {
// Hit test in reverse order so that the top most element gets hit first
for (let i = shapes.length - 1; i >= 0; i--) {
let relativePos = createVector(mouseX - shapes[i].x, mouseY - shapes[i].y);
if (pointInPoly(shapes[i].points, relativePos)) {
draggingIx = i;
draggingOffset = relativePos;
break;
}
}
}
function mouseReleased() {
draggingIx = draggingOffset = undefined;
}
function mouseDragged() {
if (draggingIx >= 0) {
shapes[draggingIx].x = mouseX - draggingOffset.x;
shapes[draggingIx].y = mouseY - draggingOffset.y;
}
}
function pointInPoly(verts, pt) {
let c = false;
// for each edge of the polygon
for (let i = 0, j = verts.length - 1; i < verts.length; j = i++) {
// Compute the slope of the edge
let slope = (verts[j].y - verts[i].y) / (verts[j].x - verts[i].x);
// If the mouse is positioned within the vertical bounds of the edge
if (((verts[i].y > pt.y) != (verts[j].y > pt.y)) &&
// And it is far enough to the right that a horizontal line from the
// left edge of the screen to the mouse would cross the edge
(pt.x > (pt.y - verts[i].y) / slope + verts[i].x)) {
// Flip the flag
c = !c;
}
}
return c;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>