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 paddle seems to magnetically pull the ball as shown in the animation:
Every time when the rectangle which surrounds the ball, collides the the paddle rectangle, the the direction of the ball is changed:
if ball.colliderect(paddleLeft):
move_x *=-1
if ball.colliderect(paddleRight):
move_x *=-1
What causes the behavior?
The issue can be reproduced with the following complete, minimal and verifiable example. The position of the ball is set so that the wrong behavior occurs immediately if the right paddle is not moved:
import pygame
pygame.init()
width, height = 600, 400
window = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
radius, move_x, move_y = 10, 3, 3
ball = pygame.Rect(width//2+125, 20, radius*2, radius)
paddleHeight = 80
paddleLeft = pygame.Rect(20, (height-paddleHeight)//2, 10, paddleHeight)
paddleRight = pygame.Rect(width-30, (height-paddleHeight)//2, 10, paddleHeight)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT: run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and paddleLeft.top > 0: paddleLeft.y -= 5
if keys[pygame.K_s] and paddleLeft.bottom < height: paddleLeft.y += 5
if keys[pygame.K_UP] and paddleRight.top > 0: paddleRight.y -= 5
if keys[pygame.K_DOWN] and paddleRight.bottom < height: paddleRight.y += 5
ball.x += move_x
ball.y += move_y
if ball.left <= 0 or ball.right >= width: move_x *=-1
if ball.top <= 0 or ball.bottom >= height: move_y *=-1
if ball.colliderect(paddleLeft): move_x *=-1
if ball.colliderect(paddleRight): move_x *=-1
window.fill(0)
pygame.draw.rect(window, (255, 255, 255), paddleLeft)
pygame.draw.rect(window, (255, 255, 255), paddleRight)
pygame.draw.circle(window, (255, 255, 255), ball.center, radius)
pygame.display.flip()
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…