Sometimes the ball doesn't bounce off the paddle in pong game

前端 未结 1 1176
不思量自难忘°
不思量自难忘° 2020-12-02 03:12

I have a simple pong game that mostly works well. But sometimes it occurs the the ball doesn\'t bounce of the paddle. The ball wobbles and slides along the paddle and the pa

相关标签:
1条回答
  • 2020-12-02 03:49

    The behavior occurs, when the ball doesn't hit the paddle at the front, but at the top or bottom. Actually the collision between the paddle and the ball is detected and the direction is changed. But the ball penetrated so deep into the paddle that the ball cannot leave the collision area with the paddle with it's next step. This causes that a collision is detected again in the next frame and the direction of the ball is changed again. Now the ball moves in the same direction as before the first collision. This process continues until the ball leaves the paddle at the bottom. This causes a zig zag movement along the front side of the paddle.

    There are different solution. One option is not to reverse the direction, but to set the direction to the left when the right paddle is hit a nd to set the direction to the right when the left paddle is hit:

    if ball.colliderect(paddleLeft):
        move_x = abs(move_x)
    if ball.colliderect(paddleRight):
        move_x = -abs(move_x) 
    

    Another option is to adjust the position to the ball. If the right paddle is hit, the right side of the ball must be placed to the left of the paddle. If the left paddle is hit, then the left side of the ball must be placed to the right of the paddle:

    if ball.colliderect(paddleLeft):
        move_x *= -1
        ball.left = paddleLeft.right
    if ball.colliderect(paddleRight):
        move_x *= -1
        ball.right = paddleRight.left
    

    0 讨论(0)
提交回复
热议问题