Home Game Development Processing 2: Creative Programming Cookbook

Processing 2: Creative Programming Cookbook

books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with Processing 2
About this book
Processing is probably the best known creative coding environment that helps you bridge the gap between programming and art. It enables designers, artists, architects, students and many others to explore graphics programming and computational art in an easy way, thus helping you boost your creativity. "Processing 2: Creative Programming Cookbook" will guide you to explore and experience the open source Processing language and environment, helping you discover advanced features and exciting possibilities with this programming environment like never before. You'll learn the basics of 2D and 3D graphics programming, and then quickly move up to advanced topics such as audio and video visualization, computer vision, and much more with this comprehensive guide. Since its birth in 2001, Processing has grown a lot. What started out as a project by Ben Fry and Casey Reas has now become a widely used graphics programming language. Processing 2 has a lot of new and exciting features. This cookbook will guide you to explore the completely new and cool graphics engine and video library. Using the recipes in this cookbook, you will be able to build interactive art for desktop computers, Internet, and even Android devices! You don't even have to use a keyboard or mouse to interact with the art you make. The book's next-gen technologies will teach you how to design interactions with a webcam or a microphone! Isn't that amazing? "Processing 2: Creative Programming Cookbook" will guide you to explore the Processing language and environment using practical and useful recipes.
Publication date:
September 2012
Publisher
Packt
Pages
306
ISBN
9781849517942

 

Chapter 1. Getting Started with Processing 2

In this chapter we will cover:

  • Installing Processing on your computer

  • Exploring the Processing Development Environment

  • Installing libraries

  • Installing tools

  • Switching modes

  • Understanding the coordinate system

  • Writing your first Processing sketch

  • Using math functions

  • Responding to mouse events

  • Responding to keyboard events

 

Introduction


In this chapter, we'll take a look at the very basics of Processing. You'll learn how to install Processing on your computer, and extend it with libraries and tools. We'll also take a glimpse at the different modes that are available in Processing 2. These things aren't very exciting, but you need to know about them before you can start creating interactive art.

But don't worry, you'll have written your first Processing sketches by the time you reach the end of the chapter. You will learn more about the structure of a Processing sketch, and we'll use some math along the way. These sketches will also teach you the basics of interaction between humans and computers. We'll use the mouse and keyboard to create simple, yet somewhat useful applications. You'll notice that programming in the Processing language probably isn't as hard as you may have thought.

 

Installing Processing on your computer


Processing is an open source programming language and environment. It can be used to create images, interactive installations, smartphone applications, and even 3D printed objects. Just about anything you can imagine. In this recipe, we'll take a look at installing Processing on Mac OS X, Windows, and Linux.

Getting ready

Download Processing 2 for your operating system at http://processing.org/download/. Processing is available for Windows, Mac OS X, and Linux. Processing for Windows comes in two flavors, one with Java and one without. Download the one with Java if you aren't sure which one to choose.

How to do it...

  • Windows: Unzip the file you've downloaded to C:\Program Files. You'll find the Processing application at C:\Program Files\Processing\. You might want to create a desktop shortcut to this app so it's easily available.

  • Mac OS X: Unzip the file you've downloaded and drag the Processing application to your Applications folder.

  • Linux: Unzip the folder to your Documents folder. Processing for Linux is a shell script. You can double-click this script and click the Run button to start Processing.

How it works...

The Processing language is built on top of Java, so you'll need a Java runtime on your computer for it to work. All versions of Mac OS X prior to 10.7 had a Java runtime installed by default. Starting with 10.7, Apple removed this. But don't worry. When you start Processing for the first time, the OS will ask you to install a Java runtime if you haven't done that already.

Processing for Windows and Linux comes with a java directory that contains everything you need to run Processing. You can however choose to use another Java runtime if you've installed one on your machine. But you should only do this if you are an advanced user and familiar with Java on one of these platforms.

There's more...

Processing uses a folder called the Sketchbook, where you will keep your sketches, libraries, and tools. Best practice is to keep this Sketchbook folder in the standard place for your OS.

  • Mac OS X: /username/Documents/Processing/

  • Windows: C:\Documents and Settings\username\My Documents\Processing\

  • Linux: /home/username/sketchbook/

 

Exploring the Processing Development Environment


When you start to work with a new application, it's important to understand the interface. In this recipe, we'll take a look at the Processing Development Environment, sometimes referred to as PDE.

How to do it...

This is the easiest thing you'll do in this book. Just open the Processing application. The following screenshot shows you what the PDE looks like on Mac OS X:

How it works...

When you open the Processing app, you'll notice that the PDE is a very basic programming environment. If you are an experienced programmer, you might miss a lot of features. The PDE was designed like this, so that people without any programming experience can get started with exploring code without having to worry about project settings, or learning a difficult interface. Let's take a look at the different interface elements.

  1. This is the run button. If you click this button, it will compile your code, and run your sketch in a new window. The shortcut for running your code is Cmd + R on the Mac, and Ctrl + R on Windows and Linux. Alternatively, you can hold down the Shift key while clicking this button to present your sketch. This will run your sketch centered on a gray fullscreen background.

  2. The stop button will terminate your sketch. You can also press the Esc key on your keyboard.

  3. Clicking the new button will create a new Processing sketch in the current window. If you want to create a sketch in a new window, you can use the File | New menu.

  4. The open button will open a menu with the names of all sketches in your sketchbook folder. This will open a sketch in the current window. If you want to open a sketch in a new window, you can use the File | Open menu.

  5. The save button will open a dialog to save your sketch.

  6. The export button will compile your sketch as an application. Holding down the Shift key will export your sketch as a Java Applet. You'll learn more about exporting your sketches in the Exporting applications in Chapter 5, Exporting from Processing recipe.

  7. This is the text editor where you will type your code.

  8. The message area is used by Processing to display messages when you save or export our sketch, or when you made a syntax error while coding.

  9. The console is used to display more detailed error messages. The output of the print() and println() functions will also appear here. You'll learn more about these functions in the Using math functions recipe later in this chapter.

 

Installing libraries


The core functionality of Processing is very basic. This was done by design, to make it easy for everyone to get started using it. If you need to do something that's not available in Processing, you can use a library that adds the functionality you need. One of the new features in Processing 2 is the Library Manager. This allows you to install new libraries in the easy way.

Getting ready

There is an overview of the available Processing libraries on the Processing website at http://processing.org/reference/libraries/. You'll find the documentation of the libraries included with Processing and a list with contributed libraries. There are libraries to work with 3D, computer vision, geometry, and a lot more.

How to do it...

You can open the library manager by using this menu: Sketch | Import Library… | Add Library…. This will give you a list of available libraries. To install the library you need to select it from the list and click on the Install button. Processing will install the library in the libraries folder of your sketchbook.

Unfortunately, not all libraries are included in this list. Some of the older libraries will probably still work in Processing 2, but the developer might not have added the new functionality to install the library through the Library Manager. In that case, you'll need to install the library manually. Don't worry; this is not as hard as it sounds.

You should download the library from the website of the developer and unzip it. Drag this folder to the libraries folder inside your sketchbook. Libraries are structured in a (predefined) way. If the library is not structured like this, it won't work. The main library folder usually contains four subfolders: examples, library, reference, and src. The examples folder contains Processing sketches the developer made to show how the library works. The library folder contains the compiled library code that will be imported into your sketch. The reference folder stores the documentation on how to use the library. The src folder contains the source code of the library. This might be handy for advanced users to learn how the library works and modify it as per their needs.

How it works...

The folder structure for libraries is important for Processing to find the library. The main folder for the colorLib library is named colorLib. Inside the library folder within that directory, you'll find a file named colorLib.jar. This JAR file will be included in your applet or application when you export your sketch. You can add import libraries into your sketch by going to the Sketch | Import Library… menu and select the library you want.

 

Installing tools


Processing tools are little applications that extend the PDE. Processing comes with a standard set of tools: a color selector, a tool to create fonts, a tool to create movies, and some other useful things.

Getting ready

There is an overview of available tools on the Processing website at http://processing.org/reference/tools/. This overview includes all standard tools and tools made by people from the Processing community. At the moment, there aren't that many tools available, but the number of quality tools might grow in the future.

How to do it...

Processing 2 has a new feature to install tools in an easy way: the Tool Manager. You can find the Tool Manager by going to Tools | Add Tool…. The Tool Manager works the same way as the Library Manager we've discussed in the Installing libraries recipe. Just like with libraries, not all tools are available in the Tool Manager. If you find a tool online, you can install it manually in the tools directory. This procedure is the same as installing a library manually. The Tool Manager looks as shown in the following screenshot:

How it works...

Tools are installed in the tools directory in your sketchbook. Each tool directory usually contains two directories, one for the tool, which contains the tool JAR file, and one with the Java source code. This JAR file is executed from the tool menu.

 

Switching modes


When Processing first came out, there was only the standard Java mode. But a lot has changed over recent years. The Processing language was ported to JavaScript by John Resig to show the capabilities of the HTML5 canvas element. Processing 2 also enables you to create apps for the Android operating system.

Getting ready

Open the Processing app. You probably already did that, since you're reading this book.

How to do it...

In the upper-right corner of the PDE, you'll see a button with the text STANDARD. If you click it, you'll get a small menu to select the other modes. Processing 2 comes with three modes: Standard, Android, and JavaScript. There is also an Add Mode… option in the menu, which will open the Mode Manager. This Mode Manager works in a similar way to the Library Manager and the Tool Manager.

How it works...

If you run a sketch in Standard mode, the PDE will compile your code and run it as a Java applet. This mode is useful if you want to create native applications that will run on a computer. Running a sketch in JavaScript mode will start a local web server on your computer, and open your default browser so you can see the sketch run within a HTML5 page. Android modewill run the sketch in the Android Emulator or on your Android device.

Note

You'll need to install the Android SDK to make this work. The color scheme of the PDE is also different in Android mode, so it's a little easier to see in which mode you are.

See also

This book also covers the new JavaScript and Android modes in depth. You can learn all about it in Chapter 9, JavaScript Mode, and Chapter 10, Exploring Android Mode.

 

Understanding the coordinate system


Before you can draw things to the screen, you need to know how the coordinate system works. Design applications might use a different point for the origin of their drawing surface. For instance, Photoshop uses the upper-left corner as (0,0), while Illustrator uses the bottom-left corner as (0,0).

Getting ready

Open Processing and create a new sketch.

How to do it...

Type this line of code in the Processing editor and press the run button. You can also use Ctrl + R (Windows, Linux) or Cmd + R (Mac OS X) to run your sketch.

size( 400, 300 );

How it works...

Processing uses the upper-left corner for the origin of the window. The size() function sets the dimensions of your sketch window. The first parameter is used to set the value of the system variable width, the second parameter is used to set the value of the system variable height.

Imagine that you want to draw a point at the bottom-right corner of the window. If you were to draw that point at (400, 300), you won't see anything on your screen. You need to draw your point at (width-1, height-1) to make it visible on screen. This may look a little strange, but it's actually very logical. If you want to draw a point at the origin, you'll use: point(0, 0);. This line of code will fill the first pixel on the first row. As we start counting at 0, the last pixel on that row would be 399, or width-1. The same is true for the height. The following screenshot shows our window of 400 by 300 pixels, divided into squares of 50 x 50 pixels.

 

Writing your first Processing sketch


In the previous recipes, you've learned all the boring stuff such as installing Processing and libraries. It's time to get your hands dirty now and write some code.

Getting ready

Create a new Processing sketch and save it as my_first_sketch to your sketch folder.

How to do it...

This is the full code for your first sketch. This sketch will draw some lines and points with varying stroke weights.

void setup()
{
  size( 640, 480 );
  smooth();
}

void draw()
{
  background(255);
  
  strokeWeight( 1 );
  point( 20, height/1.5 );
  line( 70, 20, 70, height - 20 );
  strokeWeight( 2 );
  point( 120, height/1.75 );
  line( 170, 20, 170, height - 20 );
  strokeWeight( 4 );
  point( 220, height/2 );
  line( 270, 20, 270, height - 20 );
  strokeWeight( 8 );
  point( 320, height/3 );
  line( 370, 20, 370, height - 20 );
  strokeWeight( 16 );
  point( 420, height/4 );
  line( 470, 20, 470, height - 20 );
  strokeWeight( 32 );
  point( 520, height/5 );
  line( 570, 20, 570, height - 20 );
}

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

If you run the sketch, you'll see the results of your hard work. It will look as shown in the following screenshot:

How it works...

In this recipe, you've learned the most basic functions to create a simple Processing sketch. Let's take a deeper look at what these functions do:

  • The setup() function is called only once when you run your sketch. You'll use this function to set the size of your sketch, add values to some variables, load images, and so on.

  • The draw() function is called continuously, at a rate of 60 frames per second.

  • The size() function sets the size of your sketch window. You can use size( screenWidth, screenHeight ) to create a sketch with dimensions that match the resolution of your computer screen.

  • The smooth() function is used to enable anti-aliasing. This means that all your shapes will have a soft edge. If you don't use this function, the shapes will have a more jagged edge.

  • The point() function is used to draw a point on the screen. The first parameter is the x-coordinate, the second one is the y-coordinate of the point you want to draw.

  • The line() function is used to draw a line on the screen. To draw a line, you basically need two points to define that line, as you might remember from math class in high school. The first two parameters of this function are the x and y coordinates of the first point, the third and fourth parameters are the x and y coordinates of the second point.

  • The strokeWeight() function will change the appearance of the shape you'll draw to the screen. The parameter will set the width of the stroke. For example, you can use strokeWeight(4) to draw a line with a thickness of 4 pixels.

There's more...

Processing sketches have a specific folder structure. If you save your sketch as my_first_sketch, you'll find a folder with this name in your Processing sketchbook. Inside this folder, you'll find a file named my_first_sketch.pde. Processing uses this folder structure to keep everything it needs to run the sketch together. This will be very handy when you write more complicated sketches that use more code files, or other data such as images or fonts.

 

Using math functions


You'll likely use some basic math when writing sketches with Processing. Don't worry if you forgot some of the math you learned in school, the Processing language comes with some handy functions that can do the hard work for you. But you might need to sharpen your math skills if you want to use these functions for some more advanced things such as data visualization.

Getting ready

We're going to write a small sketch that uses some of the math functions. The output of the app will be logged to the console. Start by creating a new sketch and save it as math_functions.pde.

How to do it...

This is the full code for the application we are going to write. We'll start by declaring some integer and float variables. The numbers variable is an array of floats containing the values of the variables we declared before. This sketch uses the println() function to log the output of the abs(), ceil(), floor(), round(), sq(), sqrt(), min(), max(), and dist() functions to the console.

int x = 177;
int y = -189;
float a = 32.75;
float b = -70.38;

float[] numbers = {a, b, x, y};

println("The absolute value of " + a + " is " + abs(a) );
println("The absolute value of " + b + " is " + abs(b) );
println("The absolute value of " + y + " is " + abs(y) );
println("The closest int value greater than (or equal to) " + x + " is " + ceil(x) );
println("The closest int value greater than (or equal to) " + a + " is " + ceil(a) );
println("The closest int value greater than (or equal to) " + b + " is " + ceil(b) );
println("The closest int value less than (or equal to) " + y + " is " + floor(y) );
println("The closest int value less than (or equal to) " + a + " is " + floor(a) );
println("The closest int value less than (or equal to) " + b + " is " + floor(b) );
println("The closest int value to " + a + " is " + round(a) );
println("The closest int value to " + b + " is " + round(b) );
println("The square number of " + x + " is " + sq(x) );
println("The square number of " + b + " is " + sq(b) );
println("The square root of " + x + " is " + sqrt(x) );
println("The square root of " + a + " is " + sqrt(a) );
println("The square root of " + b + " is " + sqrt(b) );
println("The smallest number in the list {" + a + "," + b + "," + x + "," + y + "} is " + min( numbers ) ); 
println("The largest number in the list {" + a + "," + b + "," + x + "," + y + "} is " + max( numbers ) ); 
println("The distance between (" + x + ", " + y + ") and (" + a + ", " + b + ") is " + dist(x, y, a, b ) );

If you run the sketch, you'll see that Processing will show an empty gray window of 100 x 100 pixels. This is the standard window size Processing uses if you don't use the size() function in a sketch. The output of the application will look as shown in the following screenshot:

How it works...

You've learned a lot of new functions to work with numbers in this recipe. Let's take a look at what they do:

  • abs() calculates the absolute value of the parameter. The result is always a positive number, so abs(-189) will return the number 189.

  • ceil() returns the closest integer value, greater than or equal to the value of the parameter. For instance, ceil(177) will return 177, ceil(-70.38) will return -70.

  • floor() returns the closest integer value, less than or equal to the value of the parameter. floor(32.75) will return 32, floor(-70.38) will return -71.

  • round() returns the closest integer value to the parameter. round(32.75) will return the number 33, round(-70.38) will return -70.

  • min() returns the smallest number from the list used as the parameter.

  • max() returns the largest number from the list used as the parameter.

  • sq() returns the square of a number. This is the same as multiplying the value of the parameter by itself. Using this function will always result in a positive number.

  • sqrt() returns the square root of a number. The value of the parameter should always be a positive number. sqrt(-70.38) will return NaN (short for Not a Number).

  • dist() calculates the distance between two points. The first two parameters are the x and y coordinates of the first point, and the third and fourth parameters are the x and y coordinates of the second point. The dist() function uses the distance formula, which is derived from the Pythagorean theorem.

There's more...

The println() function is really handy to debug your sketches. You'll use it a lot to log the value of a variable to the console. For instance, println(a) will log the value of variable a to the console. But you can also combine variables and even other functions inside the println() function, just like we did in the code for this small sketch. Let's take a look at how you can do this.

println( x + y );

This line will print the number -12 to the console. The + operator has precedence over the println() function, so the calculation will be performed first, before the println() function is executed.

println( x + " " + y );

This line will print 177 -189 to the console, and is the easiest way to print the values of the two variables to the console. In this example, the + sign inside the println() function is used to combine the values of the two variables together with the space between the two quotes into a variable of the type String.

 

Responding to mouse events


When you interact with a computer, you'll probably use a mouse. This is a standard input device on all computers that use a graphical user interface (GUI). The mouse became popular in the 1980s when Apple released the Macintosh. Most people know how to use a mouse, or trackpad, so you can easily use this to create art for people to interact with.

How to do it...

This is the full code for the sketch.

Note

Here, the draw() function is empty, as we'll do all the drawing with the mouse functions. We do need to add the draw function though, as it is used to make our app run continuously. If we leave it out of the code, the code in setup() will only run once and the app won't be interactive.

void setup()
{
  size( 640, 480 );
  smooth();
  background( 255 );
}

void draw()
{
  // empty, but we need it to create an app that runs in the continuous mode.
}

void mousePressed()
{
  if ( mouseButton == RIGHT ) {
    background( 255 );
  }
}

void mouseMoved()
{
  stroke( 0, 64 );
  strokeWeight( 1 );
  fill( 255, 32 );
  float d = dist( mouseX, mouseY, pmouseX, pmouseY );
  constrain( d, 8, 100 );
  ellipse( mouseX, mouseY, d, d );
}

void mouseDragged()
{
  stroke( 0 );
  float d = dist( mouseX, mouseY, pmouseX, pmouseY );
  constrain( d, 0, 100 );
  float w = map( d, 0, 100, 1, 10 );
  strokeWeight( w );
  line( mouseX, mouseY, pmouseX, pmouseY );
}

void mouseReleased()
{
  noStroke();
  fill( 255, 16 );
  rect( 0, 0, width, height );
}

void mouseClicked()
{
  fill( 255, 0, 0, 128 );
  float d = random( 20, 200 );
  ellipse( mouseX, mouseY, d, d );
}

After typing this code, you can run your sketch by clicking the run button or using the shortcut Cmd + R on the Mac or Ctrl + R on Windows and Linux. You can now start drawing with your mouse. When you move your mouse, you'll leave a trail of circles. When you press the mouse button and release it, you'll draw a red circle. When you move the mouse while pressing the left mouse button, you'll draw a black stroke. You can use the right mouse button to erase the screen and start all over again. The output of the application might look similar to the following screenshot:

How it works...

There are five functions and six system variables you can use to track mouse interaction in your sketch:

  • The mouseClicked() function is executed when you click a mouse button. This means pressing the button and releasing it. In the application you just made, this function was used to draw the transparent red circle.

  • The mouseDragged() function is executed when you press a mouse button and move the mouse while the button is pressed. This function is used to draw the lines in our sketch.

  • The mouseMoved() function is called every time the mouse is moved while no buttons are pressed. In our sketch, this leaves a trail of white transparent circles with a transparent black border.

  • The mousePressed() function is called when you press the button on your mouse. We use this function, together with the system variable mouseButton, to clear the screen if the right mouse button was pressed.

  • The mouseReleased() function is called when you release the mouse button. We used this function in our sketch to draw a transparent white rectangle with the size of the window on top of everything.

  • The system variable mouseX contains the current x coordinate of the mouse within the sketch window. This variable is updated every frame.

  • The system variable mouseY contains the current y coordinate of the mouse within the sketch window. This variable is updated every frame.

  • The system variable pmouseX contains the x coordinate of the mouse in the previous frame. This variable is updated every frame.

  • The system variable pmouseY contains the y coordinate of the mouse in the previous frame. This variable is updated every frame.

  • The system variable mousePressed is a boolean variable that keeps track if a mouse button is pressed or not. The value of this variable is true if a mouse button is pressed and false if no buttons are pressed.

  • The system variable mouseButton is a variable used to keep track of which mouse button is pressed. The value of this variable can be LEFT, RIGHT, or CENTER.

 

Responding to keyboard events


Another form of human-computer interaction is the keyboard. Next to the mouse, this is also one of the best-known devices to interact with computers. You can easily detect when a user presses a key, or releases it again, with Processing. One of the great things is that you can assign keys programmatically to execute pieces of code for you. This is one of the easiest ways to create a simple user-interface with Processing. For instance, you could use the D key to toggle a debug mode in your app, or the S key to save the drawing you made as an image.

How to do it...

We'll start by declaring some variables and writing the setup() and draw() functions. In this recipe, we'll write a basic Processing sketch that will change the values of the variables we've declared when we press certain keys on the keyboard.

int x;
int y;
int r;
color c;
boolean drawStroke;

void setup()
{
  size( 480, 320 );
  smooth();
  strokeWeight( 2 );
  
  x = width/2;
  y = height/2;
  r = 80;
  c = color( 255, 0, 0 );
  drawStroke = true;
}

void draw()
{
  background( 255 );
  
  if ( drawStroke == true ) {
    stroke( 0 );
  } else {
    noStroke();
  }

  fill( c );
  ellipse( x, y, r*2, r*2 );
}

The next code we'll write are the functions that will take care of the keyboard events. There are three functions we can use: keyPressed() , keyReleased() , and keyTyped().

void keyPressed()
{
  if ( key == CODED ) {
    if ( keyCode == RIGHT ) {
      x += 10;
    } else if ( keyCode == LEFT ) {
      x -= 10;
    } else if ( keyCode == UP ) {
      y -= 10;
    } else if ( keyCode == DOWN ) {
      y += 10;
    }
  }
  
  x = constrain( x, r, width-r );
  y = constrain( y, r, height-r );
  
}

void keyReleased()
{
  switch ( key ) {
    case 'r':
      c = color( 255, 0, 0 );
      break;
    case 'g':
      c = color( 0, 255, 0 );
      break;
    case 'b':
      c = color( 0, 0, 255 );
      break;
    case 'c':
      c = color( 0, 255, 255 );
      break;
    case 'm':
      c = color( 255, 0, 255 );
      break;
    case 'y':
      c = color( 255, 255, 0 );
      break;
    default:
      break;
  }
}
void keyTyped()
{
  if ( key == 's' ) {
    drawStroke = !drawStroke;
  }
}

The result of this application looks as shown in the following screenshot:

You can use the arrow keys to move the ball around. The S key will toggle the stroke. The R, G, B, C, M, and Y keys will change the color of the ball.

How it works...

There are three different functions that catch key events in Processing: keyPressed(), keyReleased(), and keyTyped(). These functions behave a little differently. The keyPressed() function is executed when you press a key. You should use this one when you need direct interaction with your application. The keyReleased() function is executed when you release the key. This will be useful when you hold a key and change something in your running application when the key is released. The keyTyped() function behaves just like the keyPressed() function, but ignores all special keys such as the arrow keys, Enter, Ctrl, and Alt.

  • The system variable key contains the value of the last key that was pressed on the keyboard.

  • The system variable keyCode is used to detect when special keys such as Shift, Ctrl, or the arrow keys are pressed. You'll most likely use this one within an if-statement that checks if the key is CODED, just like you did in the keyPressed() function in the example. The value of keyCode can be UP, DOWN, LEFT, RIGHT, ALT, CONTROL, SHIFT, BACKSPACE, TAB, ENTER, RETURN, ESC, or DELETE.

  • The system variable keyPressed is a boolean variable. The value of this variable is true if a key on the keyboard is pressed and false if no keys are pressed. This is a handy variable to use inside the draw() function.

  • The keyPressed() function is executed once when you press a key.

  • The keyReleased() function is executed once when you release a key.

  • The keyTyped() function is executed when you type a key. Keys like Alt, Ctrl, or Shift are ignored by this function.

There's more...

You've just learned how to react to single key presses. If you want to do something when a user presses multiple keys (shortcuts such as Ctrl + S to save an image), it won't work with these standard functions. There is an excellent article on the Processing Wiki that describes strategies for detecting multiple key presses at http://wiki.processing.org/w/Multiple_key_presses.

Latest Reviews (2 reviews total)
Um livro bem didático com bons exemplos, recomendo para quem quer iniciar a sua criação em Programming
Processing 2: Creative Programming Cookbook
Unlock this book and the full library FREE for 7 days
Start now