PyGame 碰撞响应错误

PyGame collision response bug

我的问题:

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

很明显,该错误是由中间的有点随机 "x" 引起的,这导致代码表现得好像角色与 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.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