var angle = 0.0;
function setup() {
createCanvas(120, 120);
background(204);
}
function draw() {
translate(mouseX, mouseY);
rotate(angle);
rect(-15, -15, 30, 30);
angle += 0.1;
}
everything works fine, but as soon as I move the var angle = 0.0; inside function draw() the rectangle will not spin. Why is that?
Why only global variable? Do built in functions/objects like rotate require global variables?
When you declare you variable inside draw() it only exists inside of it.
Also, keep in mind that draw is just a function that is called over and over during the execution of your program.
So when the program arrive at the end of your first call of draw(), it doesn’t need the variables created in it anymore and get rid of them.
During the second call, your variable angle is created again and thus, even if in your code it seems to be the same variable, it is not for the program.
I think I understand. So because there isn’t a global variable to hold the change it gets discarded at the end of the loop is that correct? I’m sure I’ll get a better understanding once I read into variable scope.
When you enter a function, some space in memory is allocated to the variables defined in that function. When you exit that function, the memory allocated is freed allowing other program to use that part of the memory.
So in your, case, what is happening is:
The draw() function is called
A variable called angle is created and set to 0
0.1 is added to the variable angle that now holds 0.1
The end of the function draw() is reached
The memory is freed so angle does not exist anymore