I have been using Processing for a week and I have created a simple pong game but I have a problem is that when the ball hit the side parts of the rectangle movable bar it shows glitches and the ball doesn’t bounce but move right through the bar. Is there anyway to resolve this? Here is my code :
float x = 400;
float y = 35;
float xdirection = random(1,2);
float ydirection = random(1,2);
float xspeed = 2;
float yspeed = 2;
boolean gameStart = false;
int point = 0;
void setup(){
size(800, 800);
background(0);
}
void draw(){
background(0);
ellipse(x ,y,55,55);
fill(255);
textSize(50);
text(point,15,50);
rect(mouseX - 75,800-25 ,150,20);
if(gameStart){
x += xspeed * xdirection;
y += yspeed * ydirection;
if(x < mouseX + 75 && x > mouseX - 75 && y > 745){
ydirection *= -1;
point += 1;
fill(255, 0, 0);
}
if (x > 775 || x < 35){
xdirection *= -1;
xspeed += 1;
}
if (y < 35){
ydirection *= -1;
yspeed += 1;
}
if (y > 800){
gameStart = false;
x = 400;
y = 35;
point = 0;
xspeed = 2;
yspeed = 2;
}
}
}
void mousePressed(){
gameStart = !gameStart;
}
The problem happens because when it touches the side of the paddle, it tries to fly up, but then it touches the paddle again on the next frame as it didn’t fly off it, and the code gets run again and again.
Solution above moves the y check down more so that it’s touchable “side” is below the screen, where the ball can never be. It’s more of a workaround, and will make the sides of your paddle intangible. It doesn’t matter much, because the pad is pretty thin, but is still something to consider.
I think I have a better solution. Replace:
if(x < mouseX + 75 && x > mouseX - 75 && y > 745)
With:
if(ydirection > 0 && x < mouseX + 75 && x > mouseX - 75 && y > 745)
So that it does the collision check only if the ball is moving down. This way, the sides will still reflect the ball’s movement, without glitching.
When you get to making another paddle at the top, make sure to check ydirection < 0 for it instead.