I need help with changing the opacity(transparency) of the objects and dragging the objects. I can change the opacity(transparency) but when I do the objects are no longer draggable.
The image below sheds more light on the question
The relevant lines for fill colour are lines 54-74
The relevant lines for dragging objects are lines 117-161
You can run and edit the code using P5.js editor,
This is the link to the code.
The correct way to implement drag and drop is to do hit-testing for the draggable objects, determine which object is being dragged, and then update the position based on the position of the mouse.
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>
FYI, the point of StackOverflow is to learn how to do something, not to ask people to write arbitrary code for you, which is why I've written some code from scratch to demonstrate how this should be done conceptually.
For more information on how the algorithm for testing if a point is inside a polygon works see this topic on the Processing.org Discourse forum.