The Draggable Box – Take 2

As I mentioned on my previous version of the Draggable Box, I had not gotten it to retain the size or position of the box when the mouse buttons were released.

Using the mouseDragged() function, I have now fixed this.

The box no longer reverts back to moving around the screen and adjusting its size on it’s own. It stays whatever size and in whatever position the user places it.

It is available online here. Click and drag with the left mouse button to move the box, or click and drag with the right mouse button to change the size. Horizontal movement affects the width and vertical movement affects the height.

int x1, x2, y1, y2;

int boxWidth=250;
int boxHeight=250;
int boxX=100;
int boxY=100;

int r=150;
int g=140;
int b=180;

void setup(){
size(500,500);
}

void draw() {
// Setup the background.
fill(0,0,250,10);
rect(0,0,width,height);

// Setup the motion.
x1 = int(random(6)-3);
x2 = int(random(6)-3);
y1 = int(random(6)-3);
y2 = int(random(6)-3);

// Changing colour assignment.
r += int(random(4)-2);
g += int(random(4)-2);
b += int(random(4)-2);

// Draw the box.
fill(r,g,b);
rect(boxX,boxY,boxWidth,boxHeight);
}

void mouseDragged() {
// Check if the left mouse button is pressed and do the following.
if (mousePressed && (mouseButton == LEFT)) {
boxX = mouseX;
boxY = mouseY;
boxWidth += x2;
boxHeight += y2;
}
// Check if the right mouse button is pressed and do the following.
else if (mousePressed && (mouseButton == RIGHT)) {
boxX += x1;
boxY += y1;
boxWidth = mouseX;
boxHeight = mouseY;
}
}

Tags: , ,

One Response to “The Draggable Box – Take 2”

  1. […] a minor fix to the draggable box I made the other day. Previously it positioned the box so that the top-left corner was aligned with […]

Leave a Reply