Update script.js
Browse files
script.js
CHANGED
|
@@ -36,43 +36,58 @@ gameArea.addEventListener('touchmove', (e) => {
|
|
| 36 |
|
| 37 |
function handlePaddleCollision(paddleY, paddleX, isLeftPaddle) {
|
| 38 |
const ballRadius = ballSize / 2;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
}
|
| 77 |
}
|
| 78 |
|
|
|
|
| 36 |
|
| 37 |
function handlePaddleCollision(paddleY, paddleX, isLeftPaddle) {
|
| 38 |
const ballRadius = ballSize / 2;
|
| 39 |
+
const paddleRight = paddleX + paddleWidth;
|
| 40 |
+
const paddleTop = paddleY;
|
| 41 |
+
const paddleBottom = paddleY + paddleHeight;
|
| 42 |
+
|
| 43 |
+
// Closest point on paddle to ball's center
|
| 44 |
+
let closestX = ballX;
|
| 45 |
+
if (isLeftPaddle) {
|
| 46 |
+
closestX = paddleRight;
|
| 47 |
+
} else {
|
| 48 |
+
closestX = paddleX;
|
| 49 |
+
}
|
| 50 |
|
| 51 |
+
let closestY = ballY;
|
| 52 |
+
if (ballY < paddleTop) {
|
| 53 |
+
closestY = paddleTop;
|
| 54 |
+
} else if (ballY > paddleBottom) {
|
| 55 |
+
closestY = paddleBottom;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// Vector from ball to closest point
|
| 59 |
+
const dx = ballX - closestX;
|
| 60 |
+
const dy = ballY - closestY;
|
| 61 |
+
const distance = Math.sqrt(dx * dx + dy * dy);
|
| 62 |
+
|
| 63 |
+
if (distance <= ballRadius) {
|
| 64 |
+
// Collision occurs
|
| 65 |
+
// Calculate normal vector
|
| 66 |
+
const normalX = isLeftPaddle ? 1 : -1;
|
| 67 |
+
const normalY = 0;
|
| 68 |
+
|
| 69 |
+
// Current velocity
|
| 70 |
+
const velocity = { x: ballSpeedX, y: ballSpeedY };
|
| 71 |
+
|
| 72 |
+
// Reflect velocity over the normal
|
| 73 |
+
const dot = velocity.x * normalX + velocity.y * normalY;
|
| 74 |
+
const reflected = {
|
| 75 |
+
x: velocity.x - 2 * dot * normalX,
|
| 76 |
+
y: velocity.y - 2 * dot * normalY
|
| 77 |
+
};
|
| 78 |
+
|
| 79 |
+
// Adjust Y velocity based on hit position
|
| 80 |
+
const hitPosition = (closestY - (paddleTop + paddleHeight / 2)) / (paddleHeight / 2);
|
| 81 |
+
const angle = hitPosition * maxAngle * (Math.PI / 180);
|
| 82 |
+
reflected.y = Math.sin(angle) * Math.abs(reflected.x);
|
| 83 |
+
|
| 84 |
+
// Set new velocity
|
| 85 |
+
ballSpeedX = reflected.x;
|
| 86 |
+
ballSpeedY = reflected.y;
|
| 87 |
+
|
| 88 |
+
// Reposition ball outside the paddle
|
| 89 |
+
const overlap = ballRadius - distance;
|
| 90 |
+
ballX += normalX * overlap;
|
| 91 |
}
|
| 92 |
}
|
| 93 |
|