# Ball Collision with Box: Booleans

So I have my ball restarting on the left once it collides to the right side of the screen. I added a red square in the center of the screen and I want the color of the square to change green when the ball touches the square.

I was suggested to use a boolean and call it “hitPaddle” but I don’t really understand how to use booleans. The “paddle” is the square and when the ball collides with the square it’s supposed to change the square’s color from red to green.

Here’s the pseudocode for the boolean:

Here’s my code:
float x = 20;
float y = 20;
float xspeed;
float yspeed;

float rectX;
float rectY;
float rectWidth;
float rectHeight;

void setup () {
size(600, 600);
xspeed = random(1.3, 4);
yspeed = random(0.3, 4);
}

void draw() {

background(0);

fill(255, 0, 0);
rectX = width/3;
rectY = height/3;
rectWidth = 200;
rectHeight = 200;

rect(rectX, rectY, rectWidth, rectHeight);

stroke(0);
fill(255);
ellipse(x +10, y +10, 20, 20);

x = x+ xspeed;
y = y+yspeed;

if (x > width - 20 || x < 0) {
x=10;
xspeed = random(1.3, 4);
}

if (y > height - 20 || y < 0) {
yspeed = yspeed * - 1;
}
}

You seem to start a new thread here - not necessary

Remarks

Your x seems to reset also when left wall

Also you don’t change xspeed and yspeed here

First you need the collision between paddle and ball.

It’s similar to the collision on the wall,
so when the ball is coming from the left side to the paddle, check if ballY is inside the paddle (meaning bigger than the upper corner of rectangle and smaller than the lower corner). Check if ballX is close to left side of paddle then reflect.

In this moment you can set a boolean variable to true - hitPaddle. Really a variable not a function.

Use this variable to determine the color of the rectangle:

``````if(hitPaddle)
fill(0,255,0);// green
else fill(255,0,0); // red
``````

Use this directly before rect() command

2 Likes