HaxeFlixel RPG tutorial: Part 16

posted on Oct 24, 2014 in Haxe, OpenFL, Game design, HaxeFlixel
HaxeFlixel RPG tutorial sound

Today I will show you how to utilize the HaxeFlixel's sound system to add sound effects to our RPG.

I'm going to add 2 sound effects to the game - a "hit" sound to play when the player attacks during combat, and a "level up" sound which is played when the player advances to a new level.

I've prepared the 2 sounds in wav format, you can download them here.

Put the sound files to the assets/sounds/ directory of your HaxeFlixel project.

Go to CombatWindow.hx and add a new variable of the FlxSound type:

private var sfx_hit:FlxSound;

We don't directly create a new sound for this, though, instead we'll use the FlxG class to load a cached sound for us. Add this to the bottom of the constructor:

sfx_hit = FlxG.sound.load("assets/sounds/hit.wav");

The sound is loaded and it can be played in onAttack() using the play() method:

private function onAttack() {
	var dmg:Int = playState.hud.getLevel();
	enemy.health -= dmg;
	txt.text = "You hit the enemy, dealing " + dmg + " damage.";
	if (enemy.health > 0) {
		var enemyDmg:Int = Math.floor(Math.random()*2);
		txt.text += "\nThe enemy strikes, dealing " + enemyDmg + " damage.";
		playState.hud.addHealth( -enemyDmg);
	} else {

And that's done! We can repeat the process in HUD.hx to add the second sound to the game.

Create a new variable in HUD:

private var sfx_levelup:FlxSound;

Instantiate it:

sfx_levelup = FlxG.sound.load("assets/sounds/levelup.wav");

And play it when the player levels up:

public function addExp(num:Int):Void {
	exp += num;
	while (exp > maxExp) {
		exp -= maxExp;
		maxExp = Math.ceil(maxExp * 1.3);

You can use the optional Flxg.sound.load() method's properties to tweak the sound's volume, repetition and other stuff.

In-game you can press the plus and minus keys to increase or decrease the volume.

You can also customize these keys using the FlxG.sound.volumeDownKeys and FlxG.sound.volumeUpKeys properties typed Array<String>.

Global sound volume can be manually set using FlxG.sound.volume, or can be muted using FlxG.sound.muted, and you can use FlxG.sound.muteKeys to set the keys that will toggle this state. The volume slider itself can be hidden using FlxG.sound.soundTrayEnabled.

That will be all for this part.

We'll add the ability to save and load the game next time!