Simple mathematics in Processing
We can use variables for many kinds of calculations, such as addition (+), division (/), subtraction (-), multiplication (*) and modulo (%). Wherever we could put a plain number, we can put a variable or mathematical statements as well:
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:
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.
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 about 60 times a second). Each screen refresh is known as a frame in the Processing terminology. 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.
With draw and setup we start running into scope issues. Variables declared inside draw are not visible in setup and vice versa. If you declare them outside of both, they're available everywhere – this is what was called local and global scope. A good rule of thumb is to declare variables only where absolutely needed instead of populating the global scope, which will often lead to trouble.
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 or testing two alternatives before deciding which one is the final one.
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 as usual:
ellipse(mouseX, mouseY, 100,100);
Create a sketch that draws circles like in the example screenshot below. For each frame, draw a slightly larger circle so that they eventually fill the whole window.
Example solution: grow.pde