Pygame碰撞检查错误

2024-09-30 00:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始在Pygame中进行Atari突破,我遇到了一个奇怪的bug。每当球碰到球拍的左侧时,它就会正常反弹,但当球在右侧时,它就会飞过球拍。请帮忙,因为我不知道怎么修

这是我的代码:

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()

Tags: poseventifdisplaymathscreenpygamerunning
1条回答
网友
1楼 · 发布于 2024-09-30 00:39:01

实际上isCollision计算包围球的矩形左上角和桨左上角之间的Euclidean distance
球员(桨)的形状是一个长方形,一边很长,一边很短。因此,碰撞算法根本不起作用。我建议使用pygame.Rect对象和colliderect来检测球和球员之间的碰撞。e、 g:

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

相关问题 更多 >

    热门问题