Menu
CoddyTech

屏幕震动

本课属于 Coddy Pygame 学习旅程的“音效与游戏体验”单元。第 12 课,共 23 课。

沉重的箱子砸到地面,整个画面会猛地晃动一下。这就是屏幕抖动:在几帧内,所有内容都会偏移几像素绘制,而且每一帧的偏移方向都不同。

要让所有内容一起移动,请将整个场景绘制到独立的 Surface 上,而不是屏幕上,然后将这个 Surface 按照偏移量 blit 到屏幕上:

world = pygame.Surface((480, 360))

在循环中,将原先使用 screen 的绘制调用改为使用 world。然后设置偏移量:

offset = (0, 0)
if shake > 0:
    amount = shake // 3
    offset = (random.randint(-amount, amount), random.randint(-amount, amount))
    shake -= 1
screen.fill((0, 0, 0))
screen.blit(world, offset)

shake 用来记录剩余的抖动帧数。落地时将它设为 12。由于 amount 是 shake // 3,最初几帧最多移动 4 像素,随后依次为 3、2、1 像素,最后停止:震动会逐渐减弱,而不是突然停止。先将屏幕填充为黑色,因为场景移动 4 像素后会留下未覆盖的窄条。

challenge icon

挑战

中等

箱子落地时,让画面抖动。

  1. 在循环之前,创建 world = pygame.Surface((480, 360))。
  2. 在 5 行绘制代码中,将 screen 改为 world。
  3. 当 shake 大于 0 时,使用 amount = shake // 3 和 random.randint(-amount, amount) 选取 x 和 y 偏移量,然后将 shake 减少 1。
  4. 将屏幕填充为黑色,并在偏移位置绘制 world。

按“开始”,再按 Space:箱子落地时,画面会抖动。然后按“检查”。

亲手试试

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Crate Drop")
clock = pygame.time.Clock()

thud_sound = pygame.mixer.Sound("assets/sounds/thud.ogg")
falling = []
landed = []
shake = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            falling.append(pygame.Rect(random.randint(140, 400), -40, 40, 40))

    for crate in falling:
        crate.y += 8
        if crate.bottom >= 300:
            crate.bottom = 300
            landed.append(crate)
            thud_sound.play()
            shake = 12
    falling = [crate for crate in falling if crate.bottom < 300]

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 80, 100), (0, 300, 480, 60))
    pygame.draw.rect(screen, (80, 160, 255), (60, 220, 30, 80))
    for crate in falling + landed:
        pygame.draw.rect(screen, (170, 110, 60), crate)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

音效与游戏体验中的所有课

自己练习: Pygame 在线编辑器