Drag and Drop an Object

Hello, I was wondering if someone could explain how I can drag and drop an object if its part of an arrayList. I know how to look if the mouse is inside or how to remove it but for a drag and drop function I really have no idea.

Thank you for the help!

Hey,

On way to do this is to have a boolean in you object to keep track if it is selected or not.
Then you move the object that are selected to your mouse position.

2 Likes

A slight variation of what was posted above using a Rectangle class:

Rect[] r;

float xOffset = 0.0;
float yOffset = 0.0;

Rect rect;

class Rect {
  float x, y, w, h;
  boolean selected;
  // Constructor
  Rect(float xpos, float ypos, float wide, float ht) {
    x = xpos;
    y = ypos;
    w = wide;
    h = ht;
  }

  void display() {
    rect(x, y, w, h);
  }
}

void setup() {
  size(800, 700);
  background(209);
  r = new Rect[10]; // initialize array
  for (int i = 0; i < r.length; i++) {
    r[i] = new Rect(random(width - 200), random(height - 150), random(200), random(150));
    r[i].selected = false;
  }
}

void draw() {
  background(209);
  for (int i = 0; i < r.length; i++) {
    r[i].display();
  }
}

void mousePressed() {
  for (int i = 0; i < r.length; i++) {
    if ((mouseX >= r[i].x) && (mouseX <= r[i].x + r[i].w) && (mouseY >= r[i].y) && (mouseY <= r[i].y + r[i].h)) {
      r[i].selected = true;
      xOffset = mouseX-r[i].x;
      yOffset = mouseY-r[i].y;
    } else {
      r[i].selected = false;
    }
  }
}

void mouseDragged() {
  for (int i = 0; i < r.length; i++) {
    if (r[i].selected == true) {
      cursor(HAND);
      r[i].x = mouseX - xOffset;
      r[i].y = mouseY - yOffset;
    }
  }
}

void mouseReleased() {
  cursor(ARROW);
}

Okay I think I understood it a bit better, but how would I do this if I have two classes of Objects that inherit from the same base Class? And they are all part of one ArrayList.