Éviter que la balle aille trop horizontal

This commit is contained in:
François Pelletier 2024-09-01 01:54:46 -04:00
parent b41f555f59
commit 3351771be7

View file

@ -117,26 +117,32 @@ function update() {
if (ball.y + ball.dy < ball.radius) {
ball.dy = -ball.dy;
} else if (ball.y + ball.dy > floorY - paddle.height) { // Changed to use floorY
if (ball.x > paddle.x && ball.x < paddle.x + paddle.width) {
if (ball.x > paddle.x-ball.radius && ball.x < paddle.x + paddle.width+ball.radius) {
// Limit the angle to a maximum of 60 degrees (pi/3 radians) from vertical
const maxAngle = Math.PI*2/3;
// Calculate where the ball hit the paddle
let hitPos = (ball.x - paddle.x) / paddle.width;
let hitPos = Math.max(0.1, Math.min(0.9, (ball.x - paddle.x) / paddle.width)) ;
console.log('Hit position:', hitPos); // Debugging purposes
// Change angle based on where the ball hit the paddle
let angle = hitPos * Math.PI - Math.PI/2;
// Limit the angle to a maximum of 45 degrees (pi/4 radians) from vertical
const maxAngle = Math.PI / 4;
angle = Math.max(-maxAngle, Math.min(maxAngle, angle));
console.log('Angle brut:', angle); // Debugging purposes
// Add some randomness to the angle (within the limited range)
angle += (Math.random() - 0.5) * Math.PI/12;
// Ensure the angle stays within the maximum limits after randomness
angle = Math.max(-maxAngle, Math.min(maxAngle, angle));
if (Math.abs(angle) < maxAngle) {
angle = Math.sign(angle) * maxAngle;
}
console.log('Angle ajusté:', angle); // Debugging purposes
// Set new velocity based on this angle
let speed = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
ball.dx = Math.cos(angle) * speed;
ball.dx = Math.cos(angle) * speed * Math.sign(angle);
ball.dy = -Math.abs(Math.sin(angle) * speed); // Ensure the ball always goes up
} else {
// Game over!