Global variables in setup()
in
Programming Questions
•
1 year ago
The sketch that I'm working on should produce a shape essentially random-walking from the center of the page; however, it doesn't seem to walk from the center of the page.
My original code is below. At first I thought that init_x and init_y needed to be defined after I set a size (so width and height were meaningful), but then draw() doesn't recognize init_x or init_y.
So I need to find a way to make the variable settings in setup() global, or perhaps there is another problem with this?
- int number_of_segments = 2000;
- float segment_width = 20;
- float time = 0;
- float init_x = width/2;
- float init_y = height/2;
- void setup(){
- size(500,500);
- smooth();
- }
- void draw(){
- background(255);
- //for every segment
- for(int i = 0; i < number_of_segments; i++){
- //generate two random numbers between -1 and 1
- float dx = 20*(1 - 2*noise(time+1));
- float dy = 20*(1 - 2*noise(time));
- if(i > 0) {
- //draw a line from (x,y) to (x+dx,y+dy);
- line(init_x,init_y,init_x+dx,init_y+dy);
- //draw a line from (x,y) to (x+dx+s,y+dy);
- line(init_x,init_y,init_x+dx+segment_width,init_y+dy);
- //draw a line from (x+s,y) to (x+s+dx,y+dy);
- line(init_x+segment_width,init_y,init_x+dx+segment_width,init_y+dy);
- }
- init_x = init_x + dx;
- init_y = init_y + dy;
- }
- time += 0.1;
- }
1