From fbd5279f2ead8ed06a56132ebef21213f9a3a22f Mon Sep 17 00:00:00 2001 From: Aonghus O Nia Date: Wed, 17 Feb 2021 00:00:32 -0500 Subject: [PATCH] Fix collision detection Change the collision detection so it only detects a collision with the left side of a paddle when traveling right and the right side of a paddle when traveling left. Otherwise occasionally when the length of the vector is adjusted after collision the ball slows down in the x direction and will not far enough to be outside the paddle after the next dt triggering a chain reaction of collisions, direction changes and shortening x velocities. --- src/pong.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/pong.js b/src/pong.js index 4a44bbd..6f652d4 100644 --- a/src/pong.js +++ b/src/pong.js @@ -133,8 +133,11 @@ class Pong } collide(player, ball) { - if (player.left < ball.right && player.right > ball.left && - player.top < ball.bottom && player.bottom > ball.top) { + if ( + ((ball.vel.x > 0 && ball.right > player.left && ball.right < player.right) || + (ball.vel.x < 0 && ball.left < player.right && ball.left > player.left)) && + player.top < ball.bottom && player.bottom > ball.top + ) { ball.vel.x = -ball.vel.x * 1.05; const len = ball.vel.len; ball.vel.y += player.vel.y * .2;