void setup () { size (842,480);frameRate(20);}
float x = random (842);
float y = random (480);
float r = random (256);
float g = random (256);
float b = random (256);
void draw () {loop ();fill (r,g,b);rect (x,y,x,y);}
thank you for the answer, Can you please give me a hint, how i can modify the code to be sure that the created rectanlges may never leave the bounds of the window?
But if the starting point of rect is for example in the middle of the screen, then, despite the restrictions in X or Y, it will still go beyond the window
Sorry, I’m not really catching up with your idea, Imagine that the rectangle will be near the maximum width and due to random () scale, it will still go beyond
(cx, cy) are the top left coordinates of the rectangle
The canvas has width and height dimensions
Then ideally if you randomly picked this point on the canvas, then what is the maximum size of the rectangle so that it doesn’t overflow the canvas?
You want to compute its max width (maximum width) and max height (maximum height) so that the random value will not be greater than that.
A pseudo code:
// Pick a random point on the canvas
float cx = random(width);
float cy = random(height);
float maxWidth = ???;
float maxHeight = ???;
float rectWidth = random(0, maxWidth);
float rectHeight = random(0, maxHeight);
// And here you have it!!
One other approach is to use a conditional if/else statement.
In pseudo: If rect x position & y position is greater than width & height then reset x position & y position to within width and height dimensions.
EDIT: But as @josephh has outlined, you will need to add width & height for the rectangles into your conditions.
Do that until the rectangle does not overflow the canvas
This solution might be inexpensive because of additional loop iterations (if it did overflow). But it’s straightforward to implement and doesn’t require any “math”.
What’s the solution to the ??? marks above?
How can you say: my max is the distance from c point to canvas right/bottom corner?
It’s an easy calculation