Using the Mouse
int x1, y1, x2, y2, x, y = -1;
int targetX, targetY;
boolean dragged = false;
color c = color(0);
void setup()
{
size(600,600);
fill (0);
noCursor();
// you can also use predefined cursors with statments like this:
// cursor(HAND);
}
void draw()
{
background(255);
fill (255);
ellipse(targetX, targetY, 20, 20);
line(targetX - 10, targetY, targetX + 10, targetY);
line(targetX, targetY - 10, targetX, targetY + 10);
if (dragged)
{
fill(c);
rect(x1, y1, x2 - x1, y2 - y1);
}
else if (y != -1 && !mousePressed)
{
fill(0);
text("You clicked at (" + x + " ," + y + ")", x, y);
}
}
/*****************************************************************
* Automatically called every time the mouse button is pressed *
*****************************************************************/
void mousePressed()
{
x1 = mouseX;
y1 = mouseY;
dragged = false;
}
/*****************************************************************
* Automatically called every time the mouse button is released *
*****************************************************************/
void mouseReleased()
{
x2 = mouseX;
y2 = mouseY;
if (x1 == x2 && y1 == y2)
dragged = false;
else
dragged = true;
}
/*****************************************************************
* Automatically called every time the mouse button is clicked *
* (ie. pressed and released at the same coordinates) *
*****************************************************************/
void mouseClicked()
{
x = mouseX;
y = mouseY;
}
/*****************************************************************
* Automatically called every time the mouse is moved with no *
* button pressed *
*****************************************************************/
void mouseMoved()
{
targetX = mouseX;
targetY = mouseY;
}
/*****************************************************************
* Automatically called every time the mouse is dragged (moved *
* with a button pressed) *
*****************************************************************/
void mouseDragged()
{
x2 = mouseX;
y2 = mouseY;
if (mouseButton == LEFT)
c = color(0);
else if (mouseButton == CENTER)
c = color(255, 0, 0);
else if (mouseButton == RIGHT)
c = color(255, 255, 0);
dragged = true;
}