python - Pygame 碰撞检查错误
问题描述
我最近开始在 Pygame 中制作 Atari Breakout,我遇到了一个奇怪的错误。每当球接触桨的左侧时,它会正常反弹,但当它在右侧时,它会飞过桨。请帮忙,因为我不知道如何解决它。
这是我的代码:
import pygame, random, math
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('Atari Breakout')
player = pygame.image.load('player copy.png')
ball = pygame.image.load('poland.png')
ballx, bally = 400, 300
balldx, balldy = 2,2
def isCollision(x1,y1,x2,y2):
distance = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))
if distance <= 32:
return True
else:
return False
running = True
while running:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pos = pygame.mouse.get_pos()
if isCollision(ballx, bally, pos[0], 525):
balldy *= -1
if bally >= 0:
balldy *= -1
if bally <= 570:
balldy *= -1
if ballx <= 0:
balldx *= -1
if ballx >= 770:
balldx *= -1
ballx += balldx
bally += balldy
screen.blit(player, (pos[0], 525))
screen.blit(ball, (ballx,bally))
pygame.display.update()
解决方案
实际上isCollision
计算了围绕球的矩形左上角和球拍左上角之间的欧几里得距离。
玩家(桨)的形状是一个长方形,边很长,边很短。因此,碰撞算法根本不起作用。我建议使用pygame.Rect
objects 和colliderect
, 来检测球和球员之间的碰撞。例如:
def isCollision(x1,y1,x2,y2):
ballRect = ball.get_rect(topleft = (x1, y1))
playerRect = player.get_rect(topleft = (x2, y2))
return ballRect.colliderect(playerRect)
while running:
# [...]
pos = pygame.mouse.get_pos()
if isCollision(ballx, bally, pos[0], 525):
balldy *= -1
推荐阅读
- spring - SRVE0278E: 添加 servlet 映射时出错 --> /*
- php - 从 DateTime 对象中分离日期属性
- javascript - 如何处理monorepo中的env文件?
- amazon-web-services - AWS 云代理配置中的 bw“start_of_file”和“end_of_file”的区别
- node.js - npm脚本中的nodemon多次触发
- postgresql - PostgreSQL 中的解释分析:对查询性能的影响?
- r - 在 R 中并行化 BMA
- delphi - TButtonItem 的 OnClick 返回 TCategoryButtons 的 Sender
- c++ - 打印时限制QStringList的长度
- python - 如何附加由分号分隔的列?