2. Variables (2), math, interaction

Recap of variables. Properties, declaration, assignment. Conflict with reserved words.

Simple mathematics in Processing

We can use variables for many kinds of calculations, such as addition (+), division (/), subtraction (-) and multiplication (*). In the mathematical statements we can use variables as well as numbers:

a=1+2;
a=b*2;
a=a+1;
a=b/3+a*3-40+c*b;

Optionally you can insert spaces to make it a bit more readable:

a = b/3 + a*3 -40 + c*b;

To see the number (will appear in the black box of the processing window) use print or println: println(a);

I’d rather not talk about these for now, but in a lot of tutorials and examples you will find things like this:

a++;
b––;

They’re only shorthand for a=a+1; and b=b-1; Use them only when you need to increment or decrement a variable by one, not in mathematic statements.

Interactive software

So far we’ve only made small sketches that are run once. For most uses we need to have the sketch running continuously. For this we need two things: setup (run once when the sketch starts) and draw (runs all the time). Things that you need once, like opening the window go under setup, things that are done continuously go under draw. This is a bit different to many other environments. An example program with setup and draw: setupdraw.pde

Comments (kommentit)

For the sake of clarity it’s essential to use comments. They serve both you and others reading your code. Comments are free-form and start with two slashes: // The rest of the line is ignored. Edit – Comment/Uncomment will do it automatically for you. Another use for comments is disabling a piece of code for testing purposes. comments.pde

Using the mouse

There are global variables named mouseX, mouseY, mousePressed and mouseButton, which you can use for simple interaction. Their values are updated automatically and they don’t need to be declared (they’re declared somewhere else). Their values can be used normally:

ellipse(mouseX, mouseY, 100,100);

An example doing something almost useful with a mouse: mousepaint.pde

Variable scope (näkyvyys)

Global variables, Local variables. Global variables are visible to all parts of the sketch. As a rule of thumb: the scope is the block enclosed in braces { }. Declaration must be done before use, too. Why are global variables bad? Different variable scopes in this example: variablescopes.pde

This entry was posted in Processing. Bookmark the permalink.