【问题标题】:How do I detect collision between the ground and a player in Pygame? [duplicate]如何在 Pygame 中检测地面和玩家之间的碰撞? [复制]
【发布时间】:2022-01-28 00:28:34
【问题描述】:

我最近开始在 Pygame 中编码,遇到了一个我真的不知道如何修复的错误,所以我真的需要一些帮助。

import pygame
from sys import exit

pygame.init()
screen = pygame.display.set_mode((800, 400))
pygame.display.set_caption('Runner')
Clock = pygame.time.Clock()
test_font = pygame.font.Font('font/Pixeltype.ttf', 50)

sky_surface = pygame.image.load('graphics/Sky.png').convert()

ground_surf = pygame.image.load('graphics/ground.png').convert()
ground_rect = ground_surf.get_rect(midbottom = (0, 300))

score_surf = test_font.render('My Game', False, (64, 64, 64))
score_rect = score_surf.get_rect(midbottom = (400, 50))

snail_surf = pygame.image.load('graphics/snail/snail1.png').convert_alpha()
snail_rect = snail_surf.get_rect(bottomright = (600, 300))

player_surf = pygame.image.load('graphics/player/player_walk_1.png').convert_alpha()
player_rect = player_surf.get_rect(midbottom = (80, 300))
player_grav = 0

ground_c = player_rect.collidepoint(ground_rect)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            player_grav = -20

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                player_grav = -20

    screen.blit(sky_surface, (0, 0))
    screen.blit(ground_surf, (0, 300))
    pygame.draw.rect(screen, "#c0e8ec", score_rect, 10)
    pygame.draw.rect(screen, "#c0e8ec", score_rect)
    screen.blit(score_surf, score_rect)

    # Snail
    snail_rect.x -= 4
    if snail_rect.right <= 0: snail_rect.left = 800
    screen.blit(snail_surf, snail_rect)
    
    # Player

    if ground_c:
        player_grav = 0
    else:
        player_grav += 1

    player_rect.y += player_grav
    screen.blit(player_surf, player_rect)


    pygame.display.update()
    Clock.tick(60)

这是我的代码,我在第 25 行收到一条错误消息,我尝试在其中创建一个冲突变量: “发生异常:TypeError 参数必须包含两个数字" 我尝试将 .y 添加到两者中,以便获得一个数字,但随后我得到: “发生异常:AttributeError 'int' 对象没有属性 'collidepoint'" 在同一条线上。有人可以告诉我为什么会发生这种情况,或者只是解释我将如何在我的场景中添加碰撞?

【问题讨论】:

标签: python pygame collision


【解决方案1】:

如果你想测试 2 个矩形(pygame.Rect 对象)的碰撞,你必须使用colliderect,而不是colidepoint

ground_c = player_rect.collidepoint(ground_rect)

ground_c = player_rect.colliderect(ground_rect)

另见How do I detect collision in pygame?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多