global vs local variables
in
Programming Questions
•
2 years ago
Hi,
I'm a novice programmer and I would be really glad if you can help me figure out this problem where I'm trying to use the system variable called width after setting the size().
Purpose of the sketch:
A sketch to explore radial placement of square boxes. Animate a box that seems to move clockwise spiraling inwards.
This code works as intended:
void setup() {smooth();size(400,400);rectMode(CENTER);}
float i = 180; // PIfloat amplitude = 200; // 400/2
void draw() {background(200);drawSquares(5, 3);}
void drawSquares(float s, int speed) {
float x = (width/2)+sin(radians(i))*amplitude;float y = (height/2)+cos(radians(i))*amplitude;
fill(0);rect(x,y,s,s);
i-=speed; //change radians at the rate of speedamplitude-=0.5; //decrease amplitude to spiral inwards
if(i==-180) {i=180; // reset radians}if(amplitude==0) {amplitude=width/2; // reset amplitude}}
However when I declare amplitude as
float amplitude = width/2;
the code does not work properly. At the start of the sketch, amplitude is 0 when I use width/2 instead of 200 or some numerical value. I was able to verify this by using text(str(amplitude),20,20) after creating and loading a font. The procedure drawSquares() is able to see the value of i and even width/2 in the line
float x = (width/2)+sin(radians(i))*amplitude;
I don't know what I'm doing wrong. Please let me know if there is a mistake in my programming or if this is a problem your are able to replicate and have found a solution for. All comments are welcome :)
Thanks,
Sam
System:
AMD Phenom II Quadcore 64bit, Windows 7, 8GB DDR3, NVIDIA 9100
1