Loading...
Logo
Processing Forum
when ever i set a variable lets say x = width and y=height/2 ......well it never freaking works....why?

for example:

Copy code
  1. void setup() {
  2. size(800,600);
  3. }
  4. int x = width/2;
  5. int y = height/2;
  6. void draw() {
  7.  ellipse(x,y,50,50);
  8. }


the ellipse will not show up in the middle of the screen for me but if i do :


Copy code
  1. void setup() {
  2. size(800,600);
  3. }
  4. //int x = width/2;
  5. //int y = height/2;
  6. void draw() {
  7.  ellipse(width/2,height/2,50,50);
  8. }


the ellipse shows up in the middle of the screen....

whyyy??

Replies(1)

This is due to the order the program is run. First the global variables are set, then setup() once, then draw() continuously. At the time of setting the global variables x and y, the values for width and height have not yet been set. The width and height are set in setup() via the size call. So you can solve your problem by setting x and y in setup() after the width and height have been set.

Adapted Code
Copy code
  1. int x, y; // here width and height are not yet set

  2. void setup() {
  3.   size(800, 600); // here width and height are set
  4.   x = width/2; // now you can use width and height
  5.   y = height/2;
  6. }

  7. void draw() {
  8.   ellipse(x, y, 50, 50); // here you could also use width and height
  9. }