我对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精灵是在主循环之前初始化的,它们看起来像这样:
player = Player(50,50,50,50)
block1 = Block1(200, 200, 100, 100)
我在mainloop的结尾处调用函数collision_test。如果需要,这是完整代码: https://pastebin.com/LTQdLMuV。
collision_test(self)
方法没有接受任何block1
参数。那个block1
是从哪里来的?在代码中你是在哪里调用这个函数的?请添加你实例化类对象并使用它们的代码部分。 - Valentino