04.04.2013 Views

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

Processing: Creative Coding and Computational Art

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

PROCESSING: CREATIVE CODING AND COMPUTATIONAL ART<br />

566<br />

detect which mouse button is pressed (left, right, or center), using <strong>Processing</strong>’s<br />

mouseButton system variable. With a little help from Java, it can also detect multiple button<br />

clicks, which I’ll illustrate in a sketch at the end of the chapter.<br />

Following is a better mouse event example, in which a rectangle on the screen is moved to<br />

the position of the mouse when the mouse button is pressed. The mouseX <strong>and</strong> mouseY<br />

properties are used to get the respective x <strong>and</strong> y positions of the mouse.<br />

// mousePressed function<br />

// example 1<br />

// declare x, y<br />

float x, y;<br />

// declare <strong>and</strong> initialize w, h<br />

float w = 20.0, h = 20.0;<br />

void setup(){<br />

size(400, 400);<br />

// initialize x, y<br />

x = width/2.0;<br />

y = height/2.0;<br />

rectMode(CENTER);<br />

}<br />

void draw(){<br />

background(255);<br />

rect(x, y, w, h);<br />

}<br />

void mousePressed() {<br />

x = mouseX;<br />

y = mouseY;<br />

}<br />

This example utilizes a function called mousePressed(). Remember, the void in front of<br />

the function identifier just means that the function doesn’t return a value. <strong>Processing</strong> also<br />

provides an alternative mousePressed Boolean variable that detects whether the mouse is<br />

pressed. The variable is equal to true if the mouse is pressed <strong>and</strong> false if it’s not. As the<br />

following code shows, the previous sketch can be easily changed to use the mousePressed<br />

variable instead of the mousePressed() function:<br />

// mousePressed variable<br />

// example 2<br />

// declare x, y<br />

float x, y;<br />

// declare <strong>and</strong> initialize w, h<br />

float w = 20.0, h = 20.0;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!