PyGame collide_rect正在检测不存在的碰撞

问题描述 投票:2回答:1

我对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))

这是我的班级应该与我的玩家碰撞的障碍。我正在碰撞检测中运行一个打印命令进行调试。就像我说的那样,它只是不断打印我给它的信息,即使它们没有碰撞。但是没有错误消息。任何帮助,将不胜感激!提前致谢 :)

编辑:

我更改了collision_test方法并添加了block1参数。现在是这样的:

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

我的播放器和block1精灵是在mainloop之前启动的,看起来像这样:

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

我在mainloop的末尾调用函数collision_test。如果您需要它,这是我的完整代码:https://pastebin.com/LTQdLMuV

python pygame collision-detection
1个回答
3
投票

发生的事情是您忘记更新对象矩形的位置。

来自pygame docs

get_rect() 得到Surface的矩形区域 get_rect(** kwargs) - > Rect 返回覆盖整个曲面的新矩形。此矩形始终从0开始,宽度为0。和高度与图像大小相同。

在这两个类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对应你屏幕上的内容。

EDIT after comments

如果你的目标是如何防止曲面之间的重叠,那就更复杂了。检测碰撞只是过程的一部分。完整的步骤是:

  • 移动玩家对象。
  • 不仅检测是否发生碰撞,还检测碰撞的两侧。
  • 一旦检测到侧面,移回该轴上的玩家对象。
  • 重绘。
© www.soinside.com 2019 - 2024. All rights reserved.