# I have a rectangle that will bounce but i want it to change colour whenever it hits a side

I cant seem to make this work but it changes colour but breaks the thing

float rectx,recty,xspeed=7,yspeed=7;
color bg = color(random(255),random(255),random(255));
void setup() {
fullScreen();
}
void draw() {
background(bg);
rect(rectx,recty,300,150);
fill(0,0,0);
if(rectx>100 || recty<100) {

``````xspeed=xspeed*-1;
bg = color(random(255),random(255),random(255));
``````

}
if(sideCollision(rectx)) {
xspeed = xspeed * -1;
}
if(topOrBottomCollision(recty)) {
yspeed = yspeed*-1;
}
rectx = rectx + xspeed;
recty = recty + yspeed;
}

boolean sideCollision(float x) {
if(x<0 || x>width-300) {
return true;
} else {
return false;
}
}

boolean topOrBottomCollision(float y) {
if(y<0 || y>height-150) {
return true;
} else {
return false;
}
}

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 );
}
``````

[UNTESTED CODE - YMMV]

Big up to you, you are amazing thanks.