Games feel much better when there is sound, no matter how simple it is. In the case of Pong, we only need one sound — when the ball hits the paddle, or when it hits the screen edge.
Before we add sound to the game, let’s assume you want to create one. You can easily do this by visiting Bfxr.net.
- Click on any sound effect button on the top-left of the app until you hear one that you like.
- Click on the effect that you want to export as a sound file on the bottom-left of the app.
- Click on “Export Wav” button on the bottom-right of the app to save the audio onto your computer.
Now we have a simple sound file, let’s use it in the game. Before we can use the sound file, we need to add the file to our assets folder.
Note: the assets/music folder is for background music — because it loops infinitely. In our case of Pong, we’re adding a sound effect. For that, we can put them in the assets/sounds folder.
Let’s insert the audio-playing code in Ball.hx itself:
class Ball extends FlxSprite
public function new(X:Float, Y:Float)
makeGraphic(30, 30, 0xFFFFFFFF);
FlxSpriteUtil.drawCircle(this, 15, 15, 15, 0xFF00FF00);
this.velocity.x = 200;
this.velocity.y = -200;
override public function update():Void
if (this.y < 0 || this.y + this.height > FlxG.stage.stageHeight)
this.velocity.y *= -1;
if (this.x + this.width < 0)
Reg.scores += 1;
if (this.x > FlxG.stage.stageWidth)
Reg.scores += 1;
public function bounce(paddle:Paddle):Void
if (hitPaddle != paddle)
this.velocity.x *= -1;
hitPaddle = paddle;
override public function destroy():Void
Here are some notes on the code above:
- In order to use FlxSound , we need to import it first, as indicated at line 5.
- We then create a class variable bounceSound at line 11.
- FlxG.sound.load() will load sound files from the assets/sounds folder automatically
- In the line 24, we load the sound when the Ball is created. In Haxe, the sound files can be loaded as a variable name rather than by string — written as AssetPaths.Hit_Hurt5__wav instead of a string value, e.g. "assets/sounds/Hit_Hurt5.wav" .
- Alternatively, instead of bounceSound.play(); , you can use FlxG.sound.play("assets/sounds/Hit_Hurt5.wav"); .
- After we have loaded the sound, we can conveniently play the sound by just using play() , as indicated on 34 and 56.
If you test the game now, there will be sound when the ball bounces! Congratulations, you have completed a simple game of Pong, minus the polish and game balancing. It’s not pretty, but it’s entertaining enough for at least a minute. 😛
In our next post, we shall wrap up with a short post-mortem of this Pong clone project and discuss some points when creating a proper game.