效果要适度
本课属于 Coddy Pygame 学习旅程的“音效与游戏体验”单元。第 15 课,共 23 课。
游戏手感就像调味料。轻微震动会让落地显得更有重量感,震动太强则会让游戏难以看清,还可能让玩家感到恶心。养成两个习惯,就能控制好震动。
限制震动幅度。效果叠加时,数值可能会不断增大。这里每次落地都会给 shake 增加 12;4 个箱子同时落地时,数值会超过 40,画面会跳动 13 像素。用 min() 为它设定上限:
shake = min(shake + 12, 18)现在,箱子不断落地时,震动持续的时间仍会变长,但移动距离不会超过 18 // 3,也就是 6 像素。
让玩家可以关闭震动。有些人无法在画面移动时玩游戏。添加一个设置只需要一个变量:
shake_on = True
...
if shake_on:
offset = (random.randint(-amount, amount), random.randint(-amount, amount))绘制完世界后,直接在屏幕上绘制标签。作为界面一部分的文字应该保持静止,不随世界一起晃动。
挑战
中等调低屏幕震动幅度,并让玩家可以将其关闭。
- 将着陆时的设置改为
shake = min(shake + 12, 18)。 - 在循环之前设置
shake_on = True;按 S 键切换它的值。只有当shake_on为 true 时,才选择随机偏移量。 - 绘制 world 后,在屏幕的
(10, 10)位置绘制Shake: On或Shake: Off。
按“开始”,然后按 S 键:屏幕上会显示 Shake: Off,物体着陆时也不再震动。然后点击“检查”。
亲手试试
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Crate Drop")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 28)
thud_sound = pygame.mixer.Sound("assets/sounds/thud.ogg")
falling = []
landed = []
shake = 0
world = pygame.Surface((480, 360))
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]
world.fill((30, 30, 46))
pygame.draw.rect(world, (80, 80, 100), (0, 300, 480, 60))
pygame.draw.rect(world, (80, 160, 255), (60, 220, 30, 80))
for crate in falling + landed:
pygame.draw.rect(world, (170, 110, 60), crate)
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)
pygame.display.flip()
clock.tick(60)
pygame.quit()
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
音效与游戏体验中的所有课
自己练习: Pygame 在线编辑器