How to use mouseClicked to only effect one object in ArrayList?

Hi all,

I am trying to make a simple game involving legos. The premise is the user presses ‘d’ to add legos and can click on them to move them around. On hovering over a lego, it changes color, and on click, the lego follows the mouse. Upon a second click, the lego is again placed. Right now, when I add only one lego, the code works fine. However, when I add more than one lego and I click on one, I grab all the legos… not just the one I clicked on. How would I only grab the one I am hovering over? I would really appreciate any help you can provide me with. Thanks!

boolean isDragging = false;
...
public void mouseClicked() {
...
 if (mode == 1) { //mode 1 is toyInteraction
    isDragging = !isDragging;
  }
}
...
private void toyInteraction() { 
  //call hoverLego, for each loop
  for (Lego lg : Legos) {
    if (lg.hoverLego()) {
      fill(255); //lego color, stroke color and weight, all when legoHover is true
      stroke(0); 
      strokeWeight(5);
    }
    if (isDragging == true) {
      //println("is dragging");
      lg.x = mouseX-lg.w/2;
      lg.y = mouseY-lg.h/2;
    }
  }
}
...
boolean hoverLego() {
    if ((x+w > mouseX && mouseX > x) && (y < mouseY && mouseY < y+h)) {
      p.disableStyle();
      return true;
    } else {
      p.enableStyle();
      return false;
    }
    //return false; //regardless of for loop, still false
  }
...

Your Lego class should have a boolean field that sets the state as “currently-being-dragged” so each Lego instance has this field and tehnically only one lego would have this state set to true. I did a demo here recently. Maybe you can sere the approach there and applied it to your use case.

Btw, the code you provide is not enough to see the problem. I suggest you provide a MCVE as it will help a ton in these cases.

Kf

Hi kfrajer, thanks for your insight, I really appreciate it!