python - Pygame 函数在 CollideRect 上不会返回 True

标签 python pygame collision

我正在尝试在 Pygame 中创建一个工作跳跃系统,但我在碰撞检测方面遇到了一些问题。我有一个级别存储在这样的列表中:

level = [
"WWWWWWWWWWWWWWWWWWWW",
"W                  W",
"W                  W",
"W                  W",
"W                  W",
"W                  W",
"W                  W",
"W                  W",
"W                  W",
"W                  W",
"WWWWWWWWWWWWWWWWWWWW",
 ]
x = y = 0
for row in level:
    for col in row:
        if col == "W":
             Wall((x, y))
        x += 32
    y += 32
    x = 0

每面墙都附加到列表中,并根据其在网格中的位置给出一个位置。

这是墙类:

class Wall (pygame.sprite.Sprite):
    def __init__(self,pos):
        pygame.sprite.Sprite.__init__(self)
        walls.append(self)
         self.rect = pygame.Rect(pos[0],pos[1],32,32)

当按下向上键并检测到玩家与其中一个图 block 之间发生碰撞时,我尝试将玩家矩形向上移动 30 像素:

if event.type == KEYDOWN and event.key == K_UP:
            if player.hitCheck():
                player.move(0,-30)

hitCheck() 是 Player 类的一个函数,如下所示:

def hitCheck(self):
    for wall in walls:
        if self.rect.colliderect(wall.rect):
            return True

但是,无论是否发生实际碰撞,该函数都不会返回 True。我可以通过将碰撞的玩家侧的值设置为相关的相对墙侧的值来移动玩家矩形,而不会穿过墙壁,但这不会产生任何结果。

为什么函数在碰撞时不返回 True?

walls 最初被声明为空列表。它用在作为玩家类一部分的移动函数中:

def move_single_axis(self, dx, dy):
    # Move the rect
    self.rect.x += dx
    self.rect.y += dy

    for wall in walls:
        if self.rect.colliderect(wall.rect):
            if dx > 0: # Moving right; Hit the left side of the wall
                self.rect.right = wall.rect.left
            if dx < 0: # Moving left; Hit the right side of the wall
                self.rect.left = wall.rect.right
            if dy > 0: # Moving down; Hit the top side of the wall
                self.rect.bottom = wall.rect.top
            if dy < 0: # Moving up; Hit the bottom side of the wall
                self.rect.top = wall.rect.bottom

这可以正常工作,这就是为什么我无法理解 hitCheck() 无法检测碰撞的原因。

最佳答案

你在哪里宣布隔离墙?它是全局变量吗?由于墙壁也是 Sprite 的一部分,因此您可以使用 spritecollide 而不是 colliderect:

def hitCheck(self):
    if pygame.sprite.spritecollide(self, self.walls):
        return True

关于python - Pygame 函数在 CollideRect 上不会返回 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25618843/

相关文章:

python - Flask、gunicorn、redis - 第 3 条路线达到 500,但 POST 在前面的步骤中有效

c++ - 2D障碍物碰撞

java - 使用另一个哈希函数处理冲突?

python - Pygame 查询 - 在同一类中生成多个 Sprite

python - 使用 Tornado 进行 RESTful 身份验证

python - 带连接的 Django ORM SELECT

python - 按类型有效地汇总项目

python - Pygame fill 直到将其移出屏幕后才会更新

Python -- Pygame 属性错误 : int object has no attribute 'draw'

python - Pygame - 尝试射击时崩溃