使rect与外观不同?

时间:2017-12-01 18:55:03

标签: python pygame

我有一个精灵,我希望有一个特定的矩形用于碰撞,但我希望它看起来比画布上的那个矩形更大。例如,如果我希望碰撞rect为(0,0,50,50),我希望屏幕上的精灵看起来好像是(0,0,70,70),作为一个例子。有没有办法区分这两者?

1 个答案:

答案 0 :(得分:1)

这是一个演示如何使用第二个矩形进行碰撞检测的示例。我定义了一个collided回调函数,用于检查hitbox es是否发生冲突而不是rect s。必须将此回调函数传递给pygame.sprite.spritecollidegroupcollide

import pygame as pg
from pygame.math import Vector2


class Player(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = pg.Surface((70, 40))
        self.image.fill(pg.Color('steelblue4'))
        self.rect = self.image.get_rect(center=pos)
        # A inflated rect as the hitbox.
        self.hitbox = self.rect.copy()
        self.hitbox.inflate_ip(-42, -22)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos
        self.hitbox.center = self.pos  # Also update the hitbox coords.


def collided(sprite, other):
    """Check if the hitboxes of the two sprites collide."""
    return sprite.hitbox.colliderect(other.hitbox)


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Player((300, 200), all_sprites)
    enemies = pg.sprite.Group(
        Player((100, 250), all_sprites),
        Player((400, 300), all_sprites),
        )

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEMOTION:
                player.pos = event.pos

        all_sprites.update()
        # Pass the custom collided callback function to spritecollide.
        collided_sprites = pg.sprite.spritecollide(
            player, enemies, False, collided)
        for sp in collided_sprites:
            print('Collision', sp)

        screen.fill((30, 30, 30))

        all_sprites.draw(screen)
        for sprite in all_sprites:
            # Draw rects and hitboxes.
            pg.draw.rect(screen, (0, 230, 0), sprite.rect, 2)
            pg.draw.rect(screen, (250, 30, 0), sprite.hitbox, 2)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()