除非你的球是一个像素,否则你可能想使用colliderect()。
为你的玩家创建一个 PyGame Rect,并使用该矩形的 (x,y) 来移动它,并对其进行 blit。球也是如此。
这可能会给你一些类似的代码:
player_img = pygame.image.load( "player.png" ).convert_alpha()
player_rect= player_img.get_rect()
player_rect.topleft = ( player_start_x, player_start_y )
ball_img = pygame.image.load( "ball.png" ).convert_alpha()
ball_rect = ball_img.get_rect()
ball_rect.topleft = ( ball_start_x, ball_start_y )
还有一个非常简单的球碰撞功能。如果参数矩形与基本矩形在几何上重叠,colliderect() 只会返回 True。由于球通常是圆形的(ish),最终您可以使用“蒙面”碰撞进行调查,这只会在图像中实际球的位置(例如,不是角落)发生碰撞 - 但现在不用担心。
def playerAtBall( player_rect, ball_rect ):
result = False
if ( player_rect.colliderect( ball_rect ) ):
result = True
return result
然后将它们放在你的主循环中:
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
# Movement keys
keys = pygame.key.get_pressed()
if ( keys[pygame.K_LEFT] ):
print("Move left")
player_rect.x -= 1
if ( keys[pygame.K_RIGHT] ):
print("Move right")
player_rect.x += 1
# Is the player at the ball?
if ( playerAtBall( player_rect, ball_rect ) ):
print( "PLAYER AT BALL - DO SOMETHING!" )
# redraw the screen
window.fill( GREEN )
window.blit( player_img, player_rect )
window.blit( ball_img, ball_rect )
pygame.display.flip()
# Clamp FPS
clock.tick_busy_loop(60)
pygame.quit()
注意:这不是经过测试、调试的代码,只是在我脑海中写下的。预计会出现拼写错误、错误等。