We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'm having issues using the height and width in my code, but only when it's being used to create a value for a variable. Here's an example of what I'm trying to run:
int x = 200;
int y = 200;
int c1 = width;
int c2 = height/2;
void setup() {
size(300, 300);
colorMode(HSB, 360, 100, 100);
frameRate(1);
background(36, 26, 98);
println(c1);
}
void draw () {
fill(random(359), random(10, 15), 99);
ellipse(width/2, c2, x, y);
}
When width is used directly as a value (like with the ellipse), it uses the actual value of 300. But when it's used to calculate a variable like c1 or c2, it defaults to the standard 100 pixels. For the println function, it will print 100 as the value for c1, but it will print 300 for the value of width or height. Am I doing something wrong?
Answers
https://forum.Processing.org/two/discussion/18107/can-t-use-width-or-height-within-an-object
is there something similar to p5.js's CreateCanvas() that I could use for Processing? Or should I just not use width or height to give value to a variable? (Thank you for the link btw!)
p5.js' createCanvas() is Processing's size().
But I was expecting you to figure out that both width & height can't be used before size()! 8-X
To underscore --
size() sets
width
andheight
-- and it should be the first line of setup, as many other things depend on it.So, this is what happens if you use width or height to initialize a global variable before setup has run:
To avoid this, assign your global variables in
setup()
after you have calledsize()
and everything will work.GoToLoop and jeremydouglass, thanks so much for helping me out! I'm almost entirely new to Processing (and code in general), and still learning how to organize everything.
I had figured that
width
andheight
aren't given a value other than 100 untilsize()
is called, but my problem was that I figured I should be putting variables outside of thesetup()
function. It worked fine for x and y, but not forwidth
andheight
. I'm guessing that's because x and y didn't rely on any information insetup()
, butwidth
andheight
did? Or should I get in the habit of only giving a value to variables when a function likesetup()
ordraw()
calls for it or directly relies on information in them?This would work fine and draw the ellipse off the bottom right corner:
But this would leave c1 and c2 at 100 and draw the ellipse in the top left:
Again, thanks for all the help!
The important concept to understand here is "variable scope". Rather than processing reading your program from top to bottom, it first reads things outside any function, then it reads things inside functions.
So, in your second example, your "int c1 = width;" is a global statement -- it gets read before setup(), even though it occurs on line 7.