Menu
CoddyTech

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

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

一度だけ再生して終了するアニメーションもあります。爆発は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に、アニメーションを1回だけ再生するupdateメソッドを追加しましょう。

  1. 5フレームごとに、explosion_framesの次の画像に進みます。
  2. 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プレイグラウンド