PyGame碰撞响应错误

特里皮

我的问题:

当我在PyGame中处理碰撞响应时,一切正常,直到我与对角线(xvel和yvel!= 0)碰撞为止。如果在检查它们各自的轴时,我有一个print(“ x”)和print(“ y”)语句,我会得到以下信息:

在此处输入图片说明

很明显,该错误是由中间的随机“ x”引起的,该错误导致代码的行为就像字符实际上与y轴碰撞时在x轴上发生碰撞。所以这真的是我的问题,为什么会这样?

这是我的碰撞响应函数:

def collide(self, direction):

    hits = pg.sprite.spritecollide(self, all_sprites_wall, False, rectconverter)
    if direction == "x":
        if hits:
            print("x")
            if self.vx > 0:
                self.hitboxrect.right = hits[0].hitboxrect.left
                self.x = self.hitboxrect.right - self.rect.width - camera.camera.x
            if self.vx < 0:
                self.hitboxrect.left = hits[0].hitboxrect.right
                self.x = self.hitboxrect.left - self.rect.width + self.hitboxrect.width - camera.camera.x
            self.rect.x = self.x

    if direction == "y":
        if hits:
            print("y")
            if self.vy > 0:
                self.hitboxrect.bottom = hits[0].hitboxrect.top
                self.y = self.hitboxrect.bottom - self.rect.height - camera.camera.y
            if self.vy < 0:
                self.hitboxrect.top = hits[0].hitboxrect.bottom
                self.y = self.hitboxrect.top - self.rect.height + self.hitboxrect.height - camera.camera.y
            self.rect.y = self.y

播放器更新功能:

def update(self):
    self.move("x")
    self.hitboxrect.x = self.x + camera.camera.x
    self.rect.x = self.x
    self.collide("x")

    self.move("y")
    self.hitboxrect.y = self.y + camera.camera.y + self.rect.height - self.hitboxrect.height
    self.rect.y = self.y
    self.collide("y")

玩家移动功能:

def move(self, direction):
    if direction == "x":
        self.x += self.vx * dt
    if direction == "y":
        self.y += self.vy * dt
特里皮

我以某种方式自己找到了答案:

问题在于我正在添加和减去摄像机值,因此通过删除摄像机x和y值,该错误消失了。我真的不确定为什么这可以解决,但我会接受。这是现在对于任何好奇的人的代码:

def collide(self, direction):
    hits = pg.sprite.spritecollide(self, all_sprites_wall, False, rectconverter)
    if direction == "x":
        if hits:
            print("x")
            if self.vx > 0:
                self.x = hits[0].hitboxrect.left - self.rect.width
                self.hitboxrect.right = hits[0].hitboxrect.left
            if self.vx < 0:
                self.x = hits[0].hitboxrect.right - self.rect.width + self.hitboxrect.width
                self.hitboxrect.left = hits[0].hitboxrect.right
            self.rect.x = self.x
    if direction == "y":
        if hits:
            print("y")
            if self.vy > 0:
                self.y = hits[0].hitboxrect.top - self.rect.height
                self.hitboxrect.bottom = hits[0].hitboxrect.top
            if self.vy < 0:
                self.y = hits[0].hitboxrect.bottom - self.rect.height + self.hitboxrect.height
                self.hitboxrect.top = hits[0].hitboxrect.bottom
            self.rect.y = self.y

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章