我对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
结果是你忘了更新对象矩形的位置。你知道吗
从pygame docs:
在
Player
和Block1
这两个类中,您都有一行代码:要使用
colliderect()
,rect
属性必须更新到屏幕上图像的位置(以像素为单位),否则draw()
方法使用的坐标与用于检查冲突的矩形之间存在不匹配。改为:因此,在创建对象时,
rect
属性对应于对象在屏幕上的实际位置。你知道吗记住在移动播放器方块时更新
player.rect
的位置。也可以编辑move_player()
函数,例如添加:所以
rect
对应于屏幕上的内容。你知道吗评论后编辑
如果你的目标是如何在表面之间进行预研磨,那就更复杂了。检测碰撞只是过程的一部分。整个步骤是:
相关问题 更多 >
编程相关推荐