【发布时间】:2019-02-21 23:44:15
【问题描述】:
我对 pygame 和一般的编码还是很陌生。我正在制作一款需要碰撞检测的游戏,但我似乎遇到了问题。每次我运行我的程序时,它都会检测到不存在的碰撞。以下是我的代码中的一些 sn-ps:
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))
这就是我的玩家应该遇到的障碍物的类。我在碰撞检测中运行打印命令进行调试。就像我说的,它只是不断地打印我给它的信息,即使它们没有发生冲突。虽然没有错误消息。任何帮助,将不胜感激!在此先感谢:)
编辑:
我更改了碰撞测试方法并添加了 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_test。如果您需要,这里是我的完整代码:https://pastebin.com/LTQdLMuV
【问题讨论】:
-
您好!您的
collision_test(self)方法不接受任何block1参数。block1来自哪里?你在代码中的什么地方调用了这个函数?请添加您从类中实例化对象并使用它们的代码部分。 -
感谢您的快速回复!刚刚编辑了我的帖子。就像我说的,我是编码新手,因此是 stackoverflow 的新手,所以我不确定在我编辑时您是否会收到通知。
-
感谢更新,我想我找到了问题所在。我会写在答案中
标签: python pygame collision-detection