X =width/2 not plotting to the middle of the sketch window

Hello,

I have a very basic question. When I set the X coordinate to width/2 and the Y coordinate to height/2, the coordinate, plotted never ends up in the middle of the screen.

Is there some coding syntax I’m missing?

I have tried setting the width and height as floats globally and this solves the problem, but I thought that the ‘width’ and ‘height’ variables were set to the ‘size’ variables of the sketch by default. Is there something I’m missing.

float X= width/2;
float Y= height/2;

void setup(){
 size(200,200);
    background(255);
}
void draw(){
  strokeWeight(12);
  rect(X,Y,10,10);
 }

In the above example I’ve used a rect but it happens for all my features( line, ellipse and so on).

2 Likes

width has a value of 0 until after size() is called.

You should set the values of X and Y inside setup() instead, after size() is called.

2 Likes

Yeah, well spotted

but you still have declare X and Y before setup()
so they are known in all functions.

float X;
float Y;
2 Likes

Thanks, I didn’t know that about ‘size’. It explains a lot about other issues I have been experiencing. Thanks again.

2 Likes

Hello,

Using println() wisely can be a great tool for understanding your code:
https://processing.org/reference/println_.html

:)

2 Likes