# Random function and constrain

Hello everybody, I’m working on a small personal exercise and I cannot undestrand how to avoid the born of random ball inside of the small square.
The idea is to fill only the white square and leave the pink-center square empty; I was thinking with map or constrain function but I never use it… Someone can help me?

CODE:

``````void setup () {
size (1000, 1000);
background (255);

rectMode (CENTER);
fill (255, 0, 0, 40);
rect (width/2, height/2, 300, 300);
}

void draw() {
float x = random (width);
float y = random (height);
fill(0,30);
ellipse (x, y, 30, 30);
}
``````
1 Like

You can either test a new ball if it’s not inside the rect and only then display it

``````
void setup () {
size (1000, 1000);
background (255);

rectMode (CENTER);
fill (255, 0, 0, 40);
rect (width/2, height/2, 300, 300);
}

void draw() {
float x = random (width);
float y = random (height);

if ( ! (x>width/2-150 && x<width/2+150)) {  // **and the y-position of the ball???? How do you have to add this?   The ! means logical NOT**
fill(0, 30);
ellipse (x, y, 30, 30);
}
}
``````

OR you just make the random values in a way that it’s automatically outside the inner rectangle, which is a bit harder, since the allowed area is AROUND the forbidden inner rectangle… (especially to distribute the points evenly)

Chrisir

1 Like

I don’t know how to manage the y position (height) in order to create the balls around the inner rectangle….

It’s the same as with x

if ( ! (x>width/2-150 && x<width/2+150 &&
y>height/2+150 && y height/2 + 150) ) {

1 Like

You may also be interested in this circle-rect collision detection demo:

1 Like