Pygame,将精灵保留在边框中,clamp_ip()无法正常工作

时间:2018-05-01 11:23:34

标签: python pygame

代码:

def main():
    running = True

    while running:

        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

        player.update()
        enemy.update(player)
        #player.rect.clamp_ip(border_rect)

        screen.fill(BACKGROUND_COLOR)
        screen.blit(player.image, player.rect)
        screen.blit(enemy.image, enemy.rect)

        pygame.display.update()




class Mob(pygame.sprite.Sprite):

    def __init__(self, position):
        super(Mob, self).__init__()

        self.image = pygame.Surface((32, 32))
        self.image.fill(pygame.Color('red'))
        self.rect = self.image.get_rect(center=position)
        self.position = pygame.math.Vector2(position)
        self.speed = 3

    def hunt_player(self, player):
        player_position = player.rect.center
        direction = player_position - self.position
        velocity = direction.normalize() * self.speed

        self.position += velocity
        self.rect.center = self.position

    def update(self, player):
        self.hunt_player(player)


class Player(pygame.sprite.Sprite):

    def __init__(self, position):
        super(Player, self).__init__()

        self.image = pygame.Surface((40, 40))
        self.image.fill(pygame.Color('blue'))
        self.rect = self.image.get_rect(center=position)

        self.position = pygame.math.Vector2(position)
        self.velocity = pygame.math.Vector2(0, 0)
        self.speed = 6

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            self.velocity.x = -self.speed
        elif keys[pygame.K_d]:
            self.velocity.x = self.speed
        else:
            self.velocity.x = 0

        if keys[pygame.K_w]:
            self.velocity.y = -self.speed
        elif keys[pygame.K_s]:
            self.velocity.y = self.speed
        else:
            self.velocity.y = 0

        self.position += self.velocity
        self.rect.center = self.position


player = Player(position=(350, 220))
enemy = Mob(position=(680, 400))

startscreen()
main()

这是一个' Chase'过去几个月我一直在涉猎的风格游戏 任何人都可以帮我为我的精灵创建边框吗?我设法使用clamp_ip()方法,但它只停止图像离开屏幕而不是实际的精灵,所以我把它拿出来了。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

player精灵的实际位置存储在self.position属性中,但调用player.rect.clamp_ip(border_rect)仅影响self.rect属性,而position仍会每一帧都要改变。

我使用pygame.Rect.contains方法检查播放器是否在屏幕区域之外,如果是,请拨打clamp_ip并将player.position设置为新{{1} }}

player.rect.center