首页 > 解决方案 > PyGame 碰撞响应错误

问题描述

我的问题:

当我在 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

标签: pythonpygame2dcollision

解决方案


不知何故,我自己找到了答案:

问题在于我正在添加和减去相机值,因此通过删除相机 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

推荐阅读