Need help with my pong program
in
Programming Questions
•
11 months ago
I am making a very simple pong program for class and I need to help making the ball bounce off my paddle on the right side of the canvas. Every time the ball hits the paddle, I want one point added to my score with the println function. If the ball misses the paddle and his the right wall, the game will end and display "GAME OVER." I'm unsure on how to do the collision so if anyone could help me with that it would be much appreciated! I'd recommend someone running my code to see exactly what it is I'm doing.
final int WIDTH = 400, HEIGHT = WIDTH;
final color WHITE = color(255);
final color BLACK = color(0);
final color RED = color(255, 0, 0);
final color GREEN = color(0, 255, 0);
final color BLUE = color(0, 0, 255);
// Ball constants
final int RAD= 5;
final int MAX_SPEED= 5;
//Pad constants
final int PAD_WIDTH= 5;
final int PAD_HEIGHT= 40;
final int PAD_X= WIDTH - PAD_WIDTH * 2;
final int PAD_SPEED= 20;
//Distance between walls and the ball
// LW= left wall distance, RW= right wall distance
// TW= top wall distance, BW= bottom wall distance
final int LW=RAD, RW = WIDTH - RAD, TW=RAD, BW= HEIGHT- RAD;
//global game variables
int ballX, ballY, speedX, speedY, PAD_Y, points;
void setup()
{
size(WIDTH, HEIGHT);
ellipseMode(RADIUS);
ballX= WIDTH/2;
ballY= HEIGHT/2;
speedX= -int(random(3, MAX_SPEED));
speedY= int(random(3, MAX_SPEED));
PAD_Y=(HEIGHT- PAD_HEIGHT) / 2;
points= 0;
}
void draw()
{
background(WHITE);
noStroke();
smooth();
fill(RED);
ellipse(ballX, ballY, RAD, RAD);
fill(BLUE);
rect(PAD_X, PAD_Y, PAD_WIDTH, PAD_HEIGHT);
ballX= ballX + speedX;
ballY= ballY + speedY;
//If the ball hits the LW, TW, or BW, it will bounce back.
if (ballX < LW) {
speedX = -speedX;
}
if (ballY < TW || ballY > BW) {
speedY = -speedY;
}
if(ballX > WIDTH || ballY > WIDTH) {
println("GAME OVER");
exit();
}
//THIS IS WHERE I'M CONFUSED
if(dist
{
{
speedX=-speedX;
speedY=-speedY;
points= points + 1;
println(points);
}
}
}
//THIS IS WHERE I'M CONFUSED
void keyPressed()
{
if (key == CODED) {
if (keyCode == UP) {
if(PAD_Y >= PAD_SPEED) {
PAD_Y -= PAD_SPEED;
}
}
else if (keyCode == DOWN) {
if(PAD_Y <= HEIGHT - PAD_HEIGHT - PAD_SPEED)
{
PAD_Y += PAD_SPEED;
}
}
}
}
1