You’re close. You should pick a new (background) color when a collision happens - not just when the rectangle is in a certain area.
float rectx, recty, xspeed=7, yspeed=7;
color bg;
void setup() {
fullScreen();
newColor();
}
void draw() {
background(bg);
// If it hits the sides, it bounces and we pick a new color.
if(sideCollision(rectx)) {
xspeed *= -1;
newColor();
}
// If it hits the top or bottom, it bounces and we pick a new color.
if(topOrBottomCollision(recty)) {
yspeed *= -1;
newColor();
}
// Move the rectangle.
rectx += xspeed;
recty += yspeed;
// Draw the rectangle.
fill(0,0,0);
rect(rectx,recty,300,150);
}
void newColor(){
bg = color(random(255),random(255),random(255));
}
boolean sideCollision(float x) {
return( x<0 || x>width-300 );
}
boolean topOrBottomCollision(float y) {
return( y<0 || y>height-150 );
}