自定义spritecollide Hitboxs

时间:2019-02-06 11:32:26

标签: python pygame

因此,我试图查看sprite与特定组中的任何对象之间是否存在任何冲突。我使用sprite.spritecollide是因为pygame方法就是这样做的,但是我想为对象而不是对象hitboxes .rect使用自定义hitboxes

def collide_hit_rect(one, two):
    return one.hit_rect.colliderect(two.rect)

def collide_hit_rect_two(one, two):
    return one.hit_rect.colliderect(two.hit_rect)

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = game.player_img
        self.rect = self.image.get_rect()
        self.hit_rect = PLAYER_HIT_RECT
        self.hit_rect.center = self.rect.center
        self.vel = vec(0, 0)
        self.pos = vec(x+0.5, y+0.5) * TILESIZE
        self.rot = 0

class Door(pg.sprite.Sprite):
    def __init__(self, game, x, y, side):
        rotation = ['R', 'U', 'L', 'D']
        self.groups = game.all_sprites, game.doors
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.side = side
        angle = rotation.index(self.side)*90
        self.image = game.door_img
        self.image = pg.transform.rotate(self.image, angle)
        self.rect = self.image.get_rect()
        if side == rotation[0]:
            self.hit_rect = pg.Rect(36, 0, 28, 64)
        elif side == rotation[1]:
            self.hit_rect = pg.Rect(0, 0, 64, 28)
        elif side == rotation[2]:
            self.hit_rect = pg.Rect(0, 0, 28, 64)
        elif side == rotation[3]:
            self.hit_rect = pg.Rect(0, 36, 64, 28)
        self.x = x
        self.y = y
        self.rect.x = self.x * TILESIZE
        self.rect.y = self.y * TILESIZE

现在,当我要检查玩家和对象的rect之间的碰撞时,可以使用碰撞 _hit_rect(),并且对于两者都正确使用sprite的{​​{1}}和对象的.hit_rect而不是.rect,例如

.rect

但是,当想要同时使用hits = pg.sprite.spritecollide(sprite, group, False, collide_hit_rect) 而不是.hit_rect检查门和玩家之间的碰撞时,这是行不通的,并且永远不会识别碰撞。

.rect

我的上门课程及其hits = pg.sprite.spritecollide(sprite, group, False, collide_hit_rect_two) 出什么问题了吗?或者可能是什么?

1 个答案:

答案 0 :(得分:0)

self.rect的位置设置在Door的构造函数的末尾:

self.rect.x = self.x * TILESIZE
self.rect.y = self.y * TILESIZE

但是self.hit_rect的位置从未设置,并且始终在(0,0)附近。设置self.hit_rect的位置,方法与使用self.rect的方法相同:

self.hit_rect.x = self.x * TILESIZE
self.hit_rect.y = self.y * TILESIZE