I’m currently in the process of making a the Pong game with JavaScript, but I cannot get the collision to work properly with the paddles - can anyone tell me where I’ve gone wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pong</title>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script src="Pong.js"></script>
</body>
</html>
let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext("2d");
let width = canvas.width;
let height = canvas.height;
const paddleWidth = 5;
const paddleHeight = 20;
const paddleOffset = 10;
let leftPaddleTop = 10;
let rightPaddleTop = 30;
document.addEventListener("mousemove", e => {
rightPaddleTop = e.y - canvas.offsetTop
});
const BALL_SIZE = 5;
let ballPosition = { x: 20, y: 30 };
let xSpeed = 4;
let ySpeed = 2;
function draw() {
//Fill canvas with black.
ctx.fillStyle = "black";
ctx.fillRect(0, 0, width, height);
//Everything else (ball) will be white.
ctx.fillStyle = "white";
//draw the ball.
ctx.fillRect(ballPosition.x, ballPosition.y, BALL_SIZE, BALL_SIZE);
//draw the paddles.
ctx.fillRect(
paddleOffset,
leftPaddleTop,
paddleWidth,
paddleHeight,
)
ctx.fillRect(
width - paddleWidth - paddleOffset,
rightPaddleTop,
paddleWidth,
paddleHeight,
)
}
function update() {
ballPosition.x += xSpeed;
ballPosition.y += ySpeed;
}
function checkPaddleCollision(ball, paddle) {
//check if the ball and paddle overlap vertically and horizontally
return(
ball.left < paddle.right &&
ball.right > paddle.left &&
ball.top < paddle.bottom &&
ball.bottom > paddle.top
);
}
function checkCollision() {
let ball = {
left: ballPosition.x,
right: ballPosition.x + BALL_SIZE,
top: ballPosition.y,
bottom: ballPosition.y + BALL_SIZE,
};
let leftPaddle = {
left: paddleOffset,
right: paddleOffset + paddleWidth,
top: leftPaddleTop,
bottom: leftPaddleTop - paddleHeight,
};
let rightPaddle = {
left: width - paddleWidth - paddleOffset,
right: width - paddleOffset,
top: rightPaddleTop,
bottom: rightPaddleTop - paddleHeight,
}
if (checkPaddleCollision(ball, leftPaddle)) {
//left paddle collision happened.
xSpeed = Math.abs(xSpeed);
};
if (checkPaddleCollision(ball, rightPaddle)) {
//right paddle collision happened.
xSpeed = Math.abs(-xSpeed);
};
if (ball.left < 0 || ball.right > width) {
xSpeed = -xSpeed;
};
if (ball.top < 0 || ball.bottom > height) {
ySpeed = -ySpeed;
};
}
function gameLoop() {
draw();
update();
checkCollision();
//call again after 30s
setTimeout(gameLoop, 30);
}
gameLoop();
I was able to get the collision to work with the boundaries of the canvas element, but I cannot seem to get the same result with the paddles.
Thanks in advance