Dragging and dropping an object

Hello! im trying to create a game where i can pick up a piece move it and then drop it where i want. I’ve run into a wall trying to logically think about dropping the piece.

in order to pick it up and move it by having it follow the mouse I did this.

function mousePressed(){
	for (let i = 0; i < pieces.length; i++){
		pieces[i].contains(mouseX, mouseY);
	}

then in my class for the piece i have this.

move(x,y){
    if (this.selected){
      this.x = x;
      this.y = y;
    }
  }

  contains(x,y){
    if (x > this.x - 30 && x < this.x + 25 && y > this.y - 30 && y < this.y + 25) {
      this.selected = true;
    }
  }

Where i call move i pass in mouseX, and mouseY as the arguments. So it works perfectly… I’ve run into a wall trying to then let the piece go and stay where i want it… My code atm is long so i’ve created a more basic example. Thanks for the help!

https://editor.p5js.org/zachmcmkay/sketches/Wdg04mmFi

2 Likes

you could try like:

function mouseReleased() {
	for (let i = 0; i < pieces.length; i++){
		pieces[i].selected = false;
	}
}
3 Likes

I had no idea mouseReleased was a function… i missed that on the reference page. Thanks man!

2 Likes