Gregniuki commited on
Commit
25cc5de
·
verified ·
1 Parent(s): 8d12a80

Update script.js

Browse files
Files changed (1) hide show
  1. script.js +20 -18
script.js CHANGED
@@ -40,12 +40,28 @@ gameArea.addEventListener('touchmove', (e) => {
40
  }
41
  });
42
 
43
- function handlePaddleCollision(paddleY, paddleXDirection) {
44
  const hitPosition = (ballY - (paddleY + paddleHeight / 2)) / (paddleHeight / 2);
45
  const angle = hitPosition * maxAngle * (Math.PI / 180); // Convert to radians
46
 
47
  ballSpeedX = paddleXDirection * Math.abs(ballSpeedX); // Ensure proper direction
48
  ballSpeedY = Math.sin(angle) * Math.abs(ballSpeedX); // Adjust vertical speed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  }
50
 
51
  function update() {
@@ -59,23 +75,9 @@ function update() {
59
  ballSpeedY = -ballSpeedY;
60
  }
61
 
62
- // Ball collision with left paddle
63
- if (
64
- ballX <= paddleWidth + 10 && // Left paddle
65
- ballY + ballSize >= paddleLeftY &&
66
- ballY <= paddleLeftY + paddleHeight
67
- ) {
68
- handlePaddleCollision(paddleLeftY, 1); // Move right
69
- }
70
-
71
- // Ball collision with right paddle
72
- if (
73
- ballX >= window.innerWidth - paddleWidth - 25 && // Right paddle
74
- ballY + ballSize >= paddleRightY &&
75
- ballY <= paddleRightY + paddleHeight
76
- ) {
77
- handlePaddleCollision(paddleRightY, -1); // Move left
78
- }
79
 
80
  // Ball out of bounds (left or right)
81
  if (ballX <= 0) {
 
40
  }
41
  });
42
 
43
+ function handlePaddleCollision(paddleY, paddleXDirection, isLeftPaddle) {
44
  const hitPosition = (ballY - (paddleY + paddleHeight / 2)) / (paddleHeight / 2);
45
  const angle = hitPosition * maxAngle * (Math.PI / 180); // Convert to radians
46
 
47
  ballSpeedX = paddleXDirection * Math.abs(ballSpeedX); // Ensure proper direction
48
  ballSpeedY = Math.sin(angle) * Math.abs(ballSpeedX); // Adjust vertical speed
49
+
50
+ // Reposition ball to ensure no clipping through paddle
51
+ if (isLeftPaddle) {
52
+ ballX = paddleWidth + 10; // Place ball just outside left paddle
53
+ } else {
54
+ ballX = window.innerWidth - paddleWidth - 25; // Place ball just outside right paddle
55
+ }
56
+ }
57
+
58
+ function checkPaddleCollision(paddleY, paddleX, isLeftPaddle) {
59
+ if (
60
+ ballX >= paddleX && ballX <= paddleX + paddleWidth &&
61
+ ballY + ballSize >= paddleY && ballY <= paddleY + paddleHeight
62
+ ) {
63
+ handlePaddleCollision(paddleY, isLeftPaddle ? 1 : -1, isLeftPaddle);
64
+ }
65
  }
66
 
67
  function update() {
 
75
  ballSpeedY = -ballSpeedY;
76
  }
77
 
78
+ // Check collision with paddles using improved detection
79
+ checkPaddleCollision(paddleLeftY, paddleWidth, true); // Left paddle
80
+ checkPaddleCollision(paddleRightY, window.innerWidth - paddleWidth - 25, false); // Right paddle
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  // Ball out of bounds (left or right)
83
  if (ballX <= 0) {