击中挡板
本课属于 Coddy Pygame 学习旅程的“项目”单元。第 14 课,共 33 课。
球碰到球拍时,应该朝相反的方向弹回。ball.colliderect(right) 会告诉你它们是否碰到了。
翻转符号 vx = -vx 有个陷阱。如果下一帧球还在球拍内部(球碰到了球拍边缘,或者球拍移动到球上),符号就会再次翻转,接着又翻转:球会在球拍里抖动。
直接设置方向,而不是翻转符号。abs(vx) 是去掉符号后的 vx,因此它始终为正数:
if ball.colliderect(left):
vx = abs(vx)
if ball.colliderect(right):
vx = -abs(vx)球离开左侧球拍时总是向右,离开右侧球拍时总是向左,无论它们接触多少帧。
挑战
中等让球从球拍上反弹。
- 球碰到墙壁反弹后,如果与
left碰撞,就设置vx = abs(vx)。 - 如果球与
right碰撞,就设置vx = -abs(vx)。
按“开始”,用右侧球拍接住球:球会反弹回来。然后点击“检查”。
亲手试试
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
left.y -= 6
if keys[pygame.K_s]:
left.y += 6
if keys[pygame.K_UP]:
right.y -= 6
if keys[pygame.K_DOWN]:
right.y += 6
left.clamp_ip(screen.get_rect())
right.clamp_ip(screen.get_rect())
ball.x += vx
ball.y += vy
if ball.top <= 0 or ball.bottom >= 400:
vy = -vy
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), left)
pygame.draw.rect(screen, (235, 80, 80), right)
pygame.draw.rect(screen, (255, 196, 0), ball)
pygame.display.flip()
clock.tick(60)
pygame.quit()
项目中的所有课
自己练习: Pygame 在线编辑器