PyGame collide\ rect正在检测不存在的碰撞

2024-04-24 04:30:57 发布

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

我对pygame还是相当陌生的,而且基本上还是编码。我正在做一个需要碰撞检测的游戏,我好像有问题。每次我运行程序时,它都会检测到不存在的碰撞。以下是我代码中的一些片段:

class Player(pygame.sprite.Sprite):
    def __init__(self,x,y,width,height):
    pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.right = False
        self.left = False
        self.up = False
        self.down = False
        self.surf = pygame.Surface((50,50))
        self.rect = self.surf.get_rect()

    def draw(self):
        pygame.draw.rect(screen, (0,0,0), (self.x, self.y, self.width, self.height))

    def collision_test(self):
        if pygame.sprite.collide_rect(self, block1):
            print("a collision is detected")

以上是我的球员课程。你知道吗

class Block1(pygame.sprite.Sprite):
    def __init__(self,x,y,width,height):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.surf = pygame.Surface((self.width,self.height))
        self.rect = self.surf.get_rect()

    def draw(self):
        pygame.draw.rect(screen, (150,150,150), (self.x, self.y, self.width, self.height))

这是我的职业,我的球员应该与障碍物相撞。我正在碰撞检测中运行print命令进行调试。就像我说的,它只是不断地打印我给它的信息,即使它们没有碰撞。但是没有错误消息。任何帮助都将不胜感激!提前感谢:)

编辑:

我更改了碰撞测试方法并添加了block1参数。现在是这样:

    def collision_test(self, block1):
        if pygame.sprite.collide_rect(self, block1):
            print("a collision is detected")

我的玩家和block1精灵在主循环之前启动,如下所示:

player = Player(50,50,50,50)
block1 = Block1(200, 200, 100, 100)

我正在调用主循环末尾的函数collision\u test。如果你需要的话,这是我的完整代码:https://pastebin.com/LTQdLMuV


Tags: recttestselffalseinitdefwidthpygame
1条回答
网友
1楼 · 发布于 2024-04-24 04:30:57

结果是你忘了更新对象矩形的位置。你知道吗

pygame docs

get_rect()
get the rectangular area of the Surface
get_rect(**kwargs)-> Rect
Returns a new rectangle covering the entire surface. This rectangle will always start at 0, 0 with a width. and height the same size as the image.

PlayerBlock1这两个类中,您都有一行代码:

self.rect = self.surf.get_rect()

要使用colliderect()rect属性必须更新到屏幕上图像的位置(以像素为单位),否则draw()方法使用的坐标与用于检查冲突的矩形之间存在不匹配。改为:

self.rect = self.surf.get_rect().move(x, y)

因此,在创建对象时,rect属性对应于对象在屏幕上的实际位置。你知道吗

记住在移动播放器方块时更新player.rect的位置。也可以编辑move_player()函数,例如添加:

player.rect.x = player.x
player.rect.y = player.y

所以rect对应于屏幕上的内容。你知道吗

评论后编辑

如果你的目标是如何在表面之间进行预研磨,那就更复杂了。检测碰撞只是过程的一部分。整个步骤是:

  • 移动播放器对象。你知道吗
  • 不仅要检测是否有碰撞,还要检测碰撞的侧面。你知道吗
  • 一旦侧边被检测到,向后移动该轴上的播放器对象。你知道吗
  • 重新绘制。你知道吗

相关问题 更多 >