3

Interaction

Always remember that this whole thing was started with a dream and a mouse.

—Walt Disney

The quality of the imagination is to flow and not to freeze.

—Ralph Waldo Emerson

In this chapter:

 The flow of a computer program

 The meaning behind setup() and draw()

 Mouse interaction

 Your first dynamic Processing sketch

 Handling events, such as mouse clicks and key presses

3-1 Go with the flow

If you have ever played a computer game, interacted with a digital art installation, or watched a screensaver at three in the morning, you have probably given very little thought to the fact that the software that runs these experiences happens over a period of time. The game starts, you find the secret treasure hidden in magical rainbow land, defeat the the scary monster who-zee-ma-whats-it, achieve a high score, and the game ends.

What I want to focus on in this chapter is that flow over time. A game begins with a set of initial conditions: you name your character, you start with a score of zero, and you start on level one. Let’s think of this part as the program’s SETUP. After these conditions are initialized, you begin to play the game. At every instant, the computer checks what you are doing with the mouse, calculates all the appropriate behaviors for the game characters, and updates the screen to render all the game graphics. This cycle of calculating and drawing happens over and over again, ideally 30 or more times per second for a smooth animation. Let’s think of this part as the program’s DRAW.

This concept is crucial to your ability to move beyond static designs (as in Chapter 2) with Processing.

1. Set starting conditions for the program one time.

2. Do something over and over and over and over (and over…) again until the program quits.

Consider how you might go about running a race.

1. Put on your sneakers and stretch. Just do this once, OK?

2. Put your right foot forward, then your left foot. Repeat this over and over as fast as you can.

3. After 26 miles, quit.

Exercise 3-1

In English, write out the flow for a simple computer game, such as Pong. If you’re not familiar with Pong, visit: http://en.wikipedia.org/wiki/Pong.

in03-01-9780123944436

___________________________

___________________________

___________________________

___________________________

3-2 Our good friends, setup() and draw()

Now that you are good and exhausted from running marathons in order to better learn programming, you can take this newfound knowledge and apply it to your first dynamic Processing sketch. Unlike Chapter 2’s static examples, this program will draw to the screen continuously (i.e., until the user quits). This is accomplished by writing two “blocks of code”: setup() and draw(). Technically speaking, setup() and draw() are functions. I will get into a longer discussion of writing your own functions in a later chapter; for now, you can understand them to be two sections where you write code.

What is a block of code?

A block of code is any code enclosed within curly brackets.

{

 A block of code

}

Blocks of code can be nested within each other, too.

{

 A block of code

 {

  A block inside a block of code

 }

}

This is an important construct as it allows you to separate and manage code as individual pieces of a larger puzzle. A programming convention is to indent the lines of code within each block to make the code more readable. Processing will do this for you via the menu option Edit → Auto-Format. Getting comfortable with organizing your code into blocks while more complex logic will prove crucial in future chapters. For now, you only need to look at two simple blocks: setup() and draw().

Let’s look at what will surely be strange-looking syntax for setup() and draw(). See Figure 3-1.

f03-01-9780123944436

Figure 3-1

Admittedly, there is a lot of stuff in Figure 3-1 that you are not entirely ready to learn about. I have covered that the curly brackets indicate the beginning and end of a block of code, but why are there parentheses after “setup” and “draw”? Oh, and, my goodness, what is this “void” all about? It makes me feel sad inside! For now, you have to decide to feel comfortable with not knowing everything all at once, and that these important pieces of syntax will start to make sense in future chapters as more concepts are revealed.

For now, the key is to focus on how Figure 3-1’s structures control the flow of a program. This is shown in Figure 3-2.

f03-02-9780123944436

Figure 3-2

How does it work? When you run the program, it will follow the instructions precisely, executing the steps in setup() first, and then move on to the steps in draw(). The order ends up being something like:

1a, 1b, 1c, 2a, 2b, 2a, 2b, 2a, 2b, 2a, 2b, 2a, 2b, 2a, 2b…

Now, I can rewrite the Zoog example as a dynamic sketch. See Example 3-1.

Example 3-1

Zoog as dynamic sketch

u03-01-9780123944436

Figure 3-3

u03-02-9780123944436

Take the code from Example 3-1 and run it in Processing. Strange, right? You will notice that nothing in the window changes. This looks identical to a static sketch! What is going on? All this discussion for nothing?

Well, if you examine the code, you will notice that nothing in the draw() function varies. Each time through the loop, the program cycles through the code and executes the identical instructions. So, yes, the program is running over time redrawing the window, but it looks static since it draws the same thing each time!

in03-01-9780123944436Exercise 3-2: Redo the drawing you created at the end of Chapter 2 as a dynamic program. Even though it will look the same, feel good about your accomplishment!

3-3 Variation with the mouse

Consider this: What if, instead of typing a number into one of the drawing functions, you could type “the mouse’s x location” or “the mouse’s y location.”

line(the mouse’s x location, the mouse’s y location, 100, 100);

In fact, you can, only instead of the more descriptive language, you must use the keywords mouseX and mouseY, indicating the horizontal or vertical position of the mouse cursor.

Example 3-2

mouseX and mouseY

u03-03-9780123944436

Figure 3-4

u03-04-9780123944436

Exercise 3-3

Explain why you see a trail of rectangles if you move background() to setup(), leaving it out of draw().

in03-01-9780123944436

___________________________

___________________________

___________________________

___________________________

___________________________

u03-05-9780123944436

An invisible line of code

If you are following the logic of setup() and draw() closely, you might arrive at an interesting question: When does Processing actually display the shapes in the window? When do the new pixels appear?

On first glance, one might assume the display is updated for every line of code that includes a drawing function. If this were the case, however, you would see the shapes appear onscreen one at a time. This would happen so fast that you would hardly notice each shape appearing individually. However, when the window is erased every time background() is called, a somewhat unfortunate and unpleasant result would occur: flicker.

Processing solves this problem by updating the window only at the end of every cycle through draw(). It’s as if there were an invisible line of code that renders the window at the end of the draw() function.

void draw() {

 // All of your code

 // Update Display Window – invisible line of code you don’t see

}

This process is known as double-buffering and, in a lower-level environment, you may find that you have to implement it yourself. Again, I’d like to take a moment to thank Processing for making our introduction to programming friendlier and simpler by taking care of this for you and me.

It should also be noted that any colors you have set with stroke() or fill() carry over from one cycle through draw() to the next.

I could push this idea a bit further and create an example where a more complex pattern (multiple shapes and colors) is controlled by mouseX and mouseY position. For example, I can rewrite Zoog to follow the mouse. Note that the center of Zoog’s body is located at the exact location of the mouse (mouseX, mouseY), however, other parts of Zoog’s body are drawn relative to the mouse. Zoog’s head, for example, is located at (mouseX, mouseY-30). The following example only moves Zoog’s body and head, as shown in Figure 3-5.

f03-03-9780123944436

Figure 3-5

Example 3-3

Zoog as dynamic sketch with variation

u03-06-9780123944436

Exercise 3-4

Complete Zoog so that the rest of its body moves with the mouse.

in03-01-9780123944436

// Draw Zoog’s eyes

fill(0);

ellipse(_______,_______, 16, 32);

ellipse(_______,_______, 16, 32);

// Draw Zoog’s legs

stroke(0);

line(_______,_______,_______,_______);

line(_______,_______,_______,_______);

in03-01-9780123944436Exercise 3-5: Recode your design so that shapes respond to the mouse (by varying color and location).

In addition to mouseX and mouseY, you can also use pmouseX and pmouseY. These two keywords stand for the previous mouseX and mouseY locations, that is, where the mouse was the last time the sketch cycled through draw(). This allows for some interesting interaction possibilities. For example, let’s consider what happens if you draw a line from the previous mouse location to the current mouse location, as illustrated in the diagram in Figure 3-6.

f03-04-9780123944436

Figure 3-6

in03-01-9780123944436Exercise 3-6: Fill in the blank in Figure 3-6.

By connecting the previous mouse location to the current mouse location with a line each time through draw(), I am able to render a continuous line that follows the mouse. See Figure 3-7.

f03-05-9780123944436

Figure 3-7

Example 3-4

Drawing a continuous line

u03-07-9780123944436

Exercise 3-7

Update Exercise 3-4 on page 40 so that the faster the user moves the mouse, the wider the drawn line. Hint: look up strokeWeight() in the Processing reference (https://processing.org/reference/strokeWeight_html).

in03-01-9780123944436

The formula for calculating the speed of the mouse’s horizontal motion is the absolute value of the difference between mouseX and pmouseX. The absolute value of a number is defined as that number without its sign:

u03-08-9780123944436

 The absolute value of -2 is 2.

 The absolute value of 2 is 2.

In Processing, you can get the absolute value of the number by placing it inside the abs() function, that is abs(-5) equals 5. The speed at which the mouse is moving is therefore:

float mouseSpeed = abs(mouseX - pmouseX);

Fill in the blank below and then try it out in Processing!

stroke(0);

_____________________________(______________);

line(pmouseX, pmouseY, mouseX, mouseY);

3-4 Mouse clicks and key presses

You are well on your way to creating dynamic, interactive Processing sketches through the use the setup() and draw() framework and the mouseX and mouseY keywords. A crucial form of interaction, however, is missing — clicking the mouse!

In order to learn how to have something happen when the mouse is clicked, you need to return to the flow of the program. You know setup() happens once and draw() loops forever. When does a mouse click occur? Mouse presses (and key presses) are considered events in Processing. If you want something to happen (such as “the background color changes to red”) when the mouse is clicked, you need to add a third block of code to handle this event.

This event “function” will tell the program what code to execute when an event occurs. As with setup(), the code will occur once and only once. That is, once and only once for each occurrence of the event. An event, such as a mouse click, can happen multiple times of course!

These are the two new functions you need:

 mousePressed() — Handles mouse clicks.

 keyPressed() — Handles key presses.

The following example uses both event functions, adding squares whenever the mouse is pressed and clearing the background whenever a key is pressed.

Example 3-5

mousePressed() and keyPressed()

u03-09-9780123944436

Figure 3-8

u03-10-9780123944436

In Exercise 3-5 on page 40, I have four functions that describe the program’s flow. The program starts in setup() where the size and background are initialized. It continues into draw(), looping endlessly. Since draw() contains no code, the window will remain blank. However, I have added two new functions: mousePressed() and keyPressed(). The code inside these functions sits and waits. When the user clicks the mouse (or presses a key), it springs into action, executing the enclosed block of instructions once and only once.

Exercise 3-8:

Add background(255); to the draw() function. Why does the program stop working?

in03-01-9780123944436

I am now ready to bring all of these elements together for Zoog.

 Zoog’s entire body will follow the mouse.

 Zoog’s eye color will be determined by mouse location.

 Zoog’s legs will be drawn from the previous mouse location to the current mouse location.

 When the mouse is clicked, a message will be displayed in the message window: “Take me to your leader!”

Note the addition in Exercise 3-6 on page 41 of the function frameRate(). frameRate(), which requires a value of at least one, enforces the speed at which Processing will cycle through draw(). frameRate(30), for example, means 30 frames per second, a traditional speed for computer animation. If you do not include frameRate(), Processing will attempt to run the sketch at 60 frames per second. Since computers run at different speeds, frameRate() is used to make sure that your sketch is consistent across multiple computers.

This frame rate is just a maximum, however. If your sketch has to draw one million rectangles, it may take a long time to finish the draw cycle and run at a slower speed.

Example 3-6

Interactive Zoog

u03-11-9780123944436

Figure 3-9

u03-12-9780123944436

Lesson One Project

in03-01-9780123944436

(You may have completed much of this project already via the exercises in Chapter 1Chapter 3. This project brings all of the elements together. You could either start from scratch with a new design or use elements from the exercises.)

1. Design a static screen drawing using RGB color and primitive shapes.

2. Make the static screen drawing dynamic by having it interact with the mouse. This might include shapes following the mouse, changing their size according to the mouse, changing their color according to the mouse, and so on.

Use the space provided below to sketch designs, notes, and pseudocode for your project.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181