【问题标题】:Pygame Custom rect for collision detection用于碰撞检测的 Pygame 自定义矩形
【发布时间】:2021-12-14 00:11:59
【问题描述】:

我已经设法使用 sprite collide 让玩家与另一个 sprite 发生碰撞并且效果很好。

但是,spritecollide 函数只允许它(至少据我所知)与名为self.rect 的矩形碰撞

我有一个名为 self.hitbox 的自定义矩形,我希望我的玩家与之发生碰撞,因为 hitbox 矩形与内置矩形本身的大小不同

这是我与 self.rect 冲突的代码

def collide_blocks(self, direction):

    hits = pygame.sprite.spritecollide(self, self.game.block_objects, False)
          
    if hits:
        for i in hits:
            if direction == "x":
              if self.x_change > 0:
                self.rect.x = i.rect.left - self.rect.width
              if self.x_change < 0:
                self.rect.x = i.rect.right 
            if direction == "y":
              if self.y_change > 0:
                self.rect.y = i.rect.top - self.rect.height 
              if self.y_change < 0:
                self.rect.y = i.rect.bottom

如何调整我的代码使其与 i.hitbox 而不是 i.rect 发生碰撞(I = 与之碰撞的精灵)

【问题讨论】:

标签: python pygame collision rectangles


【解决方案1】:

pygame.sprite.spritecollide 的第四个参数可以是用户定义的回调函数,用于计算两个精灵是否发生碰撞:

def hitbox_collide(sprite1, sprite2):
    return sprite1.hitbox.colliderect(sprite2.hitbox)
hits = pygame.sprite.spritecollide(self, self.game.block_objects, False, hitbox_collide)

【讨论】:

  • @WilliamRedding 我看不到你的代码。我给你一个笼统的答案,但你必须自己找到代码中的错误。
  • 好的,感谢您对检测的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2013-10-12
相关资源
最近更新 更多