Menu
CoddyTech

1回限りの爆発アニメーション

CoddyのPygameジャーニー「スプライトと画像」セクションの一部。レッスン 28/36。

アニメーションの中には、一度だけ再生されて終了するものがあります。爆発はexplosion_1.pngからexplosion_4.pngまでを表示して消えます。スプライトとして、独自のカウンターを進め、画像がなくなったら自分自身を削除できます。

def update(self):
    self.timer += 1
    if self.timer == 5:
        self.timer = 0
        self.index += 1
        if self.index == len(explosion_frames):
            self.kill()
        else:
            self.image = explosion_frames[self.index]

それぞれの爆発は独自のtimerとindexを持つため、異なるタイミングで始まった10個の爆発は、それぞれ最初から再生されます。必要なのはself.imageを変更することだけです。グループは、スプライトが現在保持している画像を描画します。

リストを読み取る前に終了を確認しましょう。explosion_frames[4]は存在せず、最後の画像が5フレーム表示されたら、kill()によって爆発はグループから取り除かれます。ウィンドウ内の好きな場所をクリックして、爆発を起こしてみましょう。

challenge icon

チャレンジ

中級

Explosionにupdateメソッドを追加します。5フレームごとにexplosion_framesの次の画像に切り替わり、4枚目の画像を5フレーム表示した後にself.kill()を呼び出します。

自分で試してみよう

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Explosions")
clock = pygame.time.Clock()

explosion_frames = []
for n in range(1, 5):
    explosion_frames.append(pygame.image.load(f"assets/images/explosion_{n}.png").convert_alpha())


class Explosion(pygame.sprite.Sprite):
    def __init__(self, center):
        super().__init__()
        self.index = 0
        self.timer = 0
        self.image = explosion_frames[0]
        self.rect = self.image.get_rect(center=center)


explosions = pygame.sprite.Group()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            explosions.add(Explosion(event.pos))

    explosions.update()

    screen.fill((20, 22, 40))
    explosions.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

スプライトと画像のすべてのレッスン

自分で練習してみよう: Pygameプレイグラウンド