I'm working on getting boxes to be draggable, and it works for the most part, except when the cursor gets within the bounds of another box. When that happens, that box snaps to the other. Run the code to see what I mean. I know where the problem is, but for some reason I'm having a hard time figuring out a solution--and I'm sure it's obvious too.
The problem is that I call a function to draw each box every time, and so it loops over all the boxes and doesn't differentiate between them, and thus it's like all the boxes are selected and aren't differentiated after mousePressed. I thought about sticking the boxes itself into an array or hashmap, but I don't really see a clear solution there either. It'd be nice to be able to be have the boxes overlap one another, with the last one drawn on top, but I'll take what I can get.
Here's my code. Thanks for any and all help. I really appreciate it.
Code:
Drag thing1, thing2, thing3;
int newx, newy;
boolean start;
void setup(){
size(900, 675);
background(0);
thing1 = new Drag(400,100);
thing2 = new Drag(100,100);
thing3 = new Drag(100,350);
}
void draw(){
background(0);
drawbox(thing2, 100, "two"); //light grey
drawbox(thing1, 50, "one"); //dark grey
drawbox(thing3, 255, "three"); //white
}
void drawbox(Drag item, int fillColor, String name){
item.square(fillColor);
mouseDragged(item, name);
if(start==false && mousePressed==false){
start=true;
}
}
void mouseDragged(Drag item, String name){
if(mouseX > item.getx() && mouseX < item.getx()+200 &&
mouseY > item.gety() && mouseY < item.gety()+200){
if(start==true){
newx = mouseX - item.getx();
newy = mouseY - item.gety();
start=false;
}
item.setx(mouseX-newx);
item.sety(mouseY-newy);
}
}
class Drag{
int x, y;
Drag(int coordx, int coordy){
x = coordx;
y = coordy;
}
int getx(){
return x; }
int gety(){
return y; }
void setx(int passedx){
x = passedx;
}
void sety(int passedy){
y = passedy;
}
void square(int fillColor){
fill(fillColor);
rect(x, y, 200,200);
}
}