Mouse Functions.

Mouse Functions.

Click on the box and drag it across the screen.

 
float bx;
float by;
int boxSize = 75;
boolean overBox = false;
boolean locked = false;
float xOffset = 0.0; 
float yOffset = 0.0; 

void setup() {
  size(640, 360);
  bx = width/2.0;
  by = height/2.0;
  rectMode(RADIUS);  
}

void draw() { 
  background(0);
  
  // Test if the cursor is over the box 
  if (mouseX > bx-boxSize && mouseX < bx+boxSize && 
      mouseY > by-boxSize && mouseY < by+boxSize) {
    overBox = true;  
    if(!locked) { 
      stroke(255); 
      fill(153);
    } 
  } else {
    stroke(153);
    fill(153);
    overBox = false;
  }
  
  // Draw the box
  rect(bx, by, boxSize, boxSize);
}

void mousePressed() {
  if(overBox) { 
    locked = true; 
    fill(255, 255, 255);
  } else {
    locked = false;
  }
  xOffset = mouseX-bx; 
  yOffset = mouseY-by; 

}

void mouseDragged() {
  if(locked) {
    bx = mouseX-xOffset; 
    by = mouseY-yOffset; 
  }
}

void mouseReleased() {
  locked = false;
}

Functions Used

fill()

Sets the color used to fill shapes

Learn More
stroke()

Sets the color used to draw lines and borders around shapes

Learn More
size()

Defines the dimension of the display window width and height in units of pixels

Learn More
if

Allows the program to make a decision about which code to execute

Learn More
mouseDragged()

The mouseDragged() function is called once every time the mouse moves while a mouse button is pressed

Learn More
rectMode()

Modifies the location from which rectangles are drawn by changing the way in which parameters given to rect() are intepreted

Learn More
rect()

Draws a rectangle to the screen

Learn More
setup()

The setup() function is run once, when the program starts

Learn More
mouseReleased()

The mouseReleased() function is called every time a mouse button is released

Learn More
draw()

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called

Learn More
mousePressed()

The mousePressed() function is called once after every time a mouse button is pressed

Learn More
background()

The background() function sets the color used for the background of the Processing window

Learn More