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

Update script.js

Browse files
Files changed (1) hide show
  1. script.js +10 -14
script.js CHANGED
@@ -40,6 +40,14 @@ gameArea.addEventListener('touchmove', (e) => {
40
  }
41
  });
42
 
 
 
 
 
 
 
 
 
43
  function update() {
44
  if (!isGamePaused) {
45
  // Update ball position
@@ -57,13 +65,7 @@ function update() {
57
  ballY + ballSize >= paddleLeftY &&
58
  ballY <= paddleLeftY + paddleHeight
59
  ) {
60
- // Calculate hit position (how far from the center of the paddle)
61
- const hitPosition = (ballY - (paddleLeftY + paddleHeight / 2)) / (paddleHeight / 2);
62
- // Calculate angle based on hit position (in radians)
63
- const angle = (hitPosition * maxAngle * Math.PI) / 180;
64
- // Adjust ball speed based on angle
65
- ballSpeedX = Math.abs(ballSpeedX); // Ensure ball moves right
66
- ballSpeedY = Math.tan(angle) * Math.abs(ballSpeedX); // Set vertical speed based on angle
67
  }
68
 
69
  // Ball collision with right paddle
@@ -72,13 +74,7 @@ function update() {
72
  ballY + ballSize >= paddleRightY &&
73
  ballY <= paddleRightY + paddleHeight
74
  ) {
75
- // Calculate hit position (how far from the center of the paddle)
76
- const hitPosition = (ballY - (paddleRightY + paddleHeight / 2)) / (paddleHeight / 2);
77
- // Calculate angle based on hit position (in radians)
78
- const angle = (hitPosition * maxAngle * Math.PI) / 180;
79
- // Adjust ball speed based on angle
80
- ballSpeedX = -Math.abs(ballSpeedX); // Ensure ball moves left
81
- ballSpeedY = Math.tan(angle) * Math.abs(ballSpeedX); // Set vertical speed based on angle
82
  }
83
 
84
  // Ball out of bounds (left or right)
 
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() {
52
  if (!isGamePaused) {
53
  // Update ball position
 
65
  ballY + ballSize >= paddleLeftY &&
66
  ballY <= paddleLeftY + paddleHeight
67
  ) {
68
+ handlePaddleCollision(paddleLeftY, 1); // Move right
 
 
 
 
 
 
69
  }
70
 
71
  // Ball collision with 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)