【问题标题】:Pygame hitbox collision problemsPygame 碰撞箱碰撞问题
【发布时间】:2016-12-10 12:02:17
【问题描述】:

我正在使用 Pygame 制作一个 2D 平台游戏,并且我制作了一个代码来检测我的角色是否在地板上。下面是坠落和碰撞检测的代码。

这是碰撞代码(在 Hitbox 类中):

def is_on_floor(self):
check_y = self.rect.y + self.rect.height
parent_y = self.rect.y - self.y_offset
collided = False
block_x, block_y,block_width,block_height = 0,0,0,0
points = [[self.rect.x, self.rect.y],
          [self.rect.x + self.rect.width, self.rect.y],
          [self.rect.x, self.rect.y + self.rect.height],
          [self.rect.x + self.rect.width, self.rect.y + self.rect.y]]
for obj in world:
    for point in points:
        if obj.hitbox.rect.x <= point[0] <= obj.hitbox.rect.x + obj.hitbox.rect.width and\
           obj.hitbox.rect.y <= point[1] <= obj.hitbox.rect.y + obj.hitbox.rect.height and\
           collided == False:
            block_x = obj.hitbox.rect.x
            block_y = obj.hitbox.rect.y
            block_width = obj.hitbox.rect.width
            block_height = obj.hitbox.rect.height
            collided = True
            break
    if collided:
        self.rect.y = block_y - self.rect.height
        parent_y = self.rect.y - self.y_offset
return parent_y, collided

这是下落代码(在 Player 类中):

def fall (self):
    self.y_speed += 0.4
    self.y_pos += self.y_speed
    self.hitbox.update(self.x_pos,self.y_pos)
    floor_check, collided = self.hitbox.is_on_floor()
    if collided:
        self.y_pos = floor_check
        self.can_jump = True
        self.y_speed = 0

问题是我的角色刚刚从地板上掉下来。但是,角色 确实 站在一个凸起的块上,我将其添加到关卡中以进行测试。有谁知道我该如何解决?

编辑: 为了添加新块,我正在创建块对象的副本。我试过这个:

obj = copy.copy(self)
obj.hitbox = copy.copy(self.hitbox)
world.append(obj)

但似乎当我更新块时(以便 hitbox 移动到它的位置),它更新了 一个 似乎在块对象之间共享的 hitbox。我不明白的是我使用copy.copy(self.hitbox) 来复制hitbox,但由于某种原因这似乎不起作用。

【问题讨论】:

  • 你可以用rect.bottom代替rect.y + rect.height和rect.right代替rect.x + rect.width
  • pygame 具有检查两个矩形 - rect.colliderect(other_rect) 之间以及矩形和点 rect.collidepoint(other_rect.topleft) 之间的碰撞的功能。 rect 拥有topleft、topright 等属性
  • 在检查碰撞时使用print() 查看值 - 它可以帮助发现问题。
  • 参见Program Arcade Games With Python And Pygame 和examples(即“平台示例”中的platform_jumer.py) - 他们使用pygame.sprite.Sprite() 和pygame.sprite.spritecollide()

标签: python pygame collision-detection


【解决方案1】:

我已经解决了我自己的问题 :P 看来问题是 实际上 在于我制作 hitboxes 的方式。要设置它,我输入 x、y、宽度、高度,就好像它是一个矩形一样,但我的 hitbox 类实际上需要宽度、高度、x_offset、y_offset。这意味着我不小心使碰撞框的宽度为 0,高度为 0,并且偏移量很大,这导致了奇怪的效果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多