Pygame, удерживая спрайт в рамке, Clamp_ip () не будет работать должным образом - PullRequest
0 голосов
/ 01 мая 2018

Код:

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()

Вот игра в стиле «Погони», которой я баловался последние несколько месяцев.
Может ли кто-нибудь помочь мне с созданием границы для моего спрайта? Мне удалось использовать метод Clamp_ip (), но он останавливает только то, что изображение покидает экран, а не фактический спрайт, поэтому я убрал его. Любая помощь будет высоко ценится.

1 Ответ

0 голосов
/ 01 мая 2018

Фактическая позиция спрайта player сохраняется в атрибуте self.position, но вызов player.rect.clamp_ip(border_rect) влияет только на атрибут self.rect, и position все равно будет изменяться в каждом кадре.

Я бы проверил, находится ли игрок за пределами области экрана, с помощью метода pygame.Rect.contains, если да, вызовите clamp_ip и установите player.position на новый player.rect.center.

if not border_rect.contains(player.rect):
    player.rect.clamp_ip(border_rect)
    player.position = pygame.math.Vector2(player.rect.center)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...