【问题标题】:How to use collidepoint() in pygame?如何在pygame中使用collidepoint()?
【发布时间】:2020-09-22 00:23:21
【问题描述】:

我正在制作足球游戏。 pygame 应该检测到球和玩家之间的碰撞。我不确定我是否使用了正确的功能,或者我必须使用一些逻辑来检测它。如果您确实需要使用一些逻辑。你能帮我理解一下逻辑吗?

【问题讨论】:

  • collidepoint() 用于按钮,使用 colliderect(),在你的球 x,y pos - radius 处做一个矩形

标签: pygame collision-detection


【解决方案1】:

除非你的球是一个像素,否则你可能想使用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()

注意:这不是经过测试、调试的代码,只是在我脑海中写下的。预计会出现拼写错误、错误等。

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多