Drag & drop each PGraphics shape

Hi, I am trying to drag and drop each square rather than the all of the squares when ‘x’ is pressed.

PGraphics squares;

float bx;
float by;

boolean locked = false;

float xOffset = 0.0; 
float yOffset = 0.0; 

void setup(){
  size (600, 300);
  background(0);
         
  squares = createGraphics(displayWidth, displayHeight);
}

void draw (){
  background(0);
  image(squares, bx, by);
}

void mousePressed() {
  locked = true; 
    
  xOffset = mouseX-bx; 
  yOffset = mouseY-by; 
}

void mouseDragged(){
  if(locked) {
      bx = mouseX-xOffset; 
      by = mouseY-yOffset; 
  }  
}

void mouseReleased() {
  locked = false;
}

void keyPressed (){
  if (key == 'x'){
    squares.beginDraw();
    squares.fill(160, 82, 45, random(0, 255));
    squares.noStroke();
    squares.square(random(width), random(height), random(500));
    squares.endDraw();
  }
}

Hey! From what I gather looking at your program, the way that would make the most sense to make it so you can drag/drop each shape independently would need a few things.

First off you’d need to actually make each square a separate object, as it stands currently you are just making it so all of the squares are combined into one “squares” image which you can’t really do much with.

In order to do that you’d need to find a different way to generate each square, and a way to store the location of each individual square as well, in order to do that you’d need to use either an arbitrarily large array or even better, a variable length array list.

With an arraylist filled with the locations of all of the squares you’ve generated, you can use that array/arraylist for three different things:

  1. using a loop to go through it and drawing the squares to the screen in your draw function
  2. using a loop to check if you’re currently clicking a box
  3. updating the location of a specific box

Depending on how much you already know about processing/coding in general, this could be a lot of information to take in so don’t worry if it sounds crazy.

For help with detecting if you’re clicking a square, there was a previous post that went over a fairly simple way to handle it which you can find here. make sure to look at the answer and the places it mentions overBox in the code. you could do something similar but you’d have to make it so it checks for each square individually, and for that you’d need to have all of the locations in a loop and to go through each location one by one.

Hope this helps, if there are any specific parts you don’t know about like arrays/loops, there is a lot of resources to help better understand what they are/how to use them. :smiley:

1 Like