in this p5.js code, when one draggable rectangle overlaps another, the one behind it…
- User
in this p5.js code, when one draggable rectangle overlaps another, the one behind it will also drag behind the other. I don't want them to do that. Please adjust it: let words = [ {id: 1, text: "was"}, {id: 2, text: "dog"}, {id: 3, text: "the"}, {id: 4, text: "here"}, {id: 5, text: "this"}, {id: 6, text: "morning"} ];
let boxX = 10; let boxY = 100; let boxWidth = 380; let boxHeight = 50;
function setup() { createCanvas(400, 200); textAlign(CENTER, CENTER); textSize(18);
// Scatter words randomly on the canvas for (let word of words) { word.x = random(10, width - 110); word.y = random(50, height - 50); word.draggable = null; } }
function draw() { background(220);
// Draw the box fill(255); rect(boxX, boxY, boxWidth, boxHeight);
for (let word of words) { if (word.draggable) { word.x = mouseX; word.y = mouseY; }
fill(255); rect(word.x - 10, word.y - 10, textWidth(word.text) + 20, 30); fill(0); text(word.text, word.x + textWidth(word.text) / 2, word.y);} }
function mousePressed() { for (let word of words) { let wordWidth = textWidth(word.text); if (mouseX > word.x - 10 && mouseX < word.x + wordWidth + 10 && mouseY > word.y - 10 && mouseY < word.y + 20) { word.draggable = true; } } }
function mouseReleased() { for (let word of words) { word.draggable = false; } }
function mouseClicked() { let correctOrder = [3, 2, 1, 4, 5, 6]; let wordPositions = words .filter(word => word.y > boxY && word.y < boxY + boxHeight) .sort((a, b) => a.x - b.x) .map(word => word.id);
if (wordPositions.toString() == correctOrder.toString()) { alert("Congratulations! The sentence is correct!"); } }
- Assistant
To fix the overlapping issue, we can introduce a "dragOffset" to store the relative distance between the top-left corner of a draggable rectangle and the mouse pointer when you start dragging it. With this offset, the dragging behavior will look more natural, and the rectangles won't overlap each other when dragging.