Drag & Drop PGraphics

Hi, I am trying to move the square to another position but it forms a streak of squares instead when dragged.

Here is what I have so far:

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);
    
         squares.beginDraw();
         squares.fill(160, 82, 45, random(0, 255));
         squares.noStroke();
         squares.square(random(width), random(height), random(500));
         squares.endDraw();
}

void draw (){
  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;
}


Hello,

You need to clean your screen before drawing something else on it. Otherwise, it keep adding to the previous frame:

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

You’re right, I overlooked that. Thank you!

1 Like