Declaring variables which use system variables

Hi,

The following code doesn't work as I would expect it to. Each of my variables appears to return a value of 0. Is it because outside of void draw(), system variables (eg width and height) have no meaning? Many thanks

Matt

float rect_width = width / 8;
float rect_height = height / 8;
float xpos = width / 4;
float ypos = height / 2;
float ell_width = width / 3;
float ell_height = height / 3;

void setup() {
  size(200, 200);
  frameRate(30);
}

void draw() {
  background(255);
  stroke(0);
  fill(127);
  rectMode(CENTER);
  ellipseMode(CENTER);
  rect(xpos, ypos, rect_width, rect_height);
  rect(xpos*3, ypos, rect_width, rect_height);
  ellipse(xpos * 2, ypos, ell_width, ell_height);


}

Answers

  • Your global variables get set immediately.

    Then setup() runs, which calls size().

    The values of width and height are only set after size() is called.

    You should do your variable assignments in setup().

  • edited July 2015

    Not only both width & height are 0 before setup(), sketchPath is null.
    Therefore anything depending on those 3 variables fails before setup().
    Anything else should work hopefully! :D

  • Thanks for your help guys :)

  • TfGuy44, I followed your advice: "You should do your variable assignments in setup()."

    My new code is below but it still won't run because: Syntax error on token "float", package expected

    Any ideas?

    Many thanks,

    Matt

    float rect_width;
    float rect_height;
    float xpos;
    float ypos;
    float ell_width;
    float ell_height;
    
    void setup() {
    
      size(200, 200);
      rect_width = width / 8;
      rect_height = height / 8;
      xpos = width / 4;
      ypos = height / 2;
      ell_width = width / 3;
      ell_height = height / 3;
    
    }
    
    void draw() {
      background(255);
      stroke(0);
      fill(127);
      rectMode(CENTER);
      ellipseMode(CENTER);
    
      rect(xpos, ypos, rect_width, rect_height);
      rect(xpos*3, ypos, rect_width, rect_height);
      ellipse(xpos * 2, ypos, ell_width, ell_height);
    
    
    }
    
  • It compiles & runs for me! :-\"

  • Hmm, mysterious. Doesn't work for me.

  • Wait! Saved it out to a different filename and it works now :)

  • And what was the old name?

Sign In or Register to comment.