Godot进行2D游戏开发入门-音效管理器

前言

游戏的音乐可以只有一个,但是音效可以同时播放多个,并且多个音效可能是同一个。

音效管理器

添加场景

添加场景AudioManager

image-20230801001314077

绑定脚本

添加脚本AudioManager.gd

添加脚本并绑定到场景AudioManager上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
extends Node

var curr = 0
var total = 10
var soundMap = {}

func _ready():
for i in range(total):
self.add_child(AudioStreamPlayer.new())
soundMap["laser_gun"] = load("res://assets/sound/laser_gun.mp3")
soundMap["pistol"] = load("res://assets/sound/pistol.mp3")

func play(name : String):
var sfx = self.get_child(curr)
if sfx is AudioStreamPlayer:
if(soundMap[name]):
sfx.stream = soundMap[name]
sfx.play()
curr = (curr+1)%total

自动加载

项目 => 项目设置 => 自动加载

添加音频管理的场景

image-20230801001453919

调用

这样在其他任何页面都可以调用了

1
2
3
4
5
6
func _unhandled_input(event):
if event is InputEventKey:
if event.pressed and event.keycode == KEY_J:
AudioManager.play("pistol")
if event.pressed and event.keycode == KEY_K:
AudioManager.play("laser_gun")