06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

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.

Setup:<br />

Draw:<br />

Initialize car color.<br />

Initialize car location <strong>to</strong> starting point.<br />

Initialize car speed.<br />

Fill background.<br />

Display car at location with color.<br />

Increment car’s location by speed.<br />

Objects 123<br />

In Chapter 7, we defi ned global variables at the <strong>to</strong>p of the program, initialized them in setup( ) , and called<br />

functions <strong>to</strong> move and display the car in draw( ) .<br />

Object-oriented programming allows us <strong>to</strong> take all of the variables and functions out of the main<br />

program and s<strong>to</strong>re them inside a car object. A car object will know about its data— color , location , speed .<br />

Th at is part one. Part two of the car object is the stuff it can do, the methods (functions inside an object).<br />

Th e car can move and it can be displayed .<br />

Using object-oriented design, the pseudocode improves <strong>to</strong> look something like this:<br />

Data (Global Variables):<br />

Setup:<br />

Draw:<br />

Car object.<br />

Initialize car object.<br />

Fill background.<br />

Display car object.<br />

Move car object.<br />

Notice we removed all of the global variables from the fi rst example. Instead of having separate variables for<br />

car color, car location, and car speed, we now have only one variable, a Car variable! And instead of initializing<br />

those three variables, we initialize one thing, the Car object. Where did those variables go? Th ey still exist, only<br />

now they live inside of the Car object (and will be defi ned in the Car class, which we will get <strong>to</strong> in a moment).<br />

Moving beyond pseudocode, the actual body of the sketch might look like:<br />

Car myCar;<br />

void setup() {<br />

myCar = new Car();<br />

}<br />

void draw() {<br />

background(0);<br />

myCar.move();<br />

myCar.display();<br />

}<br />

An object in <strong>Processing</strong>.<br />

We are going <strong>to</strong> get in<strong>to</strong> the details regarding the previous code in a moment, but before we do so, let’s<br />

take a look at how the Car class itself is written.

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

Saved successfully!

Ooh no, something went wrong!