Home > Back-end >  Processing Drag-and-Drop Class/Object
Processing Drag-and-Drop Class/Object

Time:12-18

I'm currently trying to make a class in Processing that allows the user to create objects that can be dragged and dropped. It's not that hard to create individual objects, but I've had some trouble implementing them into a class so that the user can create as many as they wish. Do you have any guidance?

Here is the code I have so far.

dragndrop.pde

void setup() {
  size(800, 600);
}

void draw() {
  background(80);
  noStroke();
  DragObject d = new DragObject(width/2, height/2, 50, 245);
  d.run();
}

DragObject.pde

class DragObject {
  int x;
  int y;
  int r;
  color col;
  
  DragObject(int xx, int yy, int rr, int c) {
    x = xx;
    y = yy;
    r = rr;
    col = c;
  }
  
  void run() {
    if(mouseX > (x - r/2) && mouseX < (x   r/2) && mouseY > (y - r/2) && mouseY < (y   r/2)) {
      if(mousePressed) {
        x = mouseX;
        y = mouseY;
      } 
    }
    fill(col);
    circle(x, y, r);
  }
}

It lets you drag the circle, but only as long as the mouse is within the circle's radius.

Thank you!

CodePudding user response:

The following code will allow you to drag the object around the screen. In order to have multiple circles you will need to create an object array, eg DragObject[] d; and then initialize it for as many as you want in setup(), eg d = new DragObject[numOfObjects];

int xOffset = 0;
int yOffset = 0;

DragObject d;

void setup() {
  size(800, 600);
  d = new DragObject(width/2, height/2, 50, 245);
}

void draw() {
  background(80);
  noStroke();
  d.display();
}

void mousePressed() {
  if (mouseX > (d.x - d.r) && mouseX < (d.x   d.r) && mouseY > (d.y - d.r) && mouseY < (d.y   d.r)) {
    xOffset = mouseX-d.x;
    yOffset = mouseY-d.y;
  }
}

void mouseDragged() {
  d.x = mouseX - xOffset;
  d.y = mouseY - yOffset;
}

class DragObject {
  int x;
  int y;
  int r;
  color col;

  DragObject(int xx, int yy, int rr, int c) {
    x = xx;
    y = yy;
    r = rr;
    col = c;
  }

  void display() {
    fill(col);
    circle(x, y, r);
  }
}

  • Related