You are here: JGT Tutorial >
9. Sounds
Lesson 4: Sounds and Explosions
Sounds
We want to add explosions when the enemies die. First, the sound.
For sounds, we use JGT's SimpleClip. It is a simple wrapper around Java's javax.sound.sampled.Clip class. We give a file name to the constructor to load a sound, and use the play() method to play the sound.
We add three sounds to the game, and load them at the beginning.
public class MyGame extends BaseApp {
SimpleClip _boom, _fire, _destroyed;
(...)
/** game entry point **/
public void run() {
try {
// sound by "bliss" (on Freesound.iua.upf.edu)
_boom = new SimpleClip("gamedata/boom.wav");
_fire = new SimpleClip("gamedata/wuw1.wav");
// sound by "meatball4u" (on Freesound.iua.upf.edu)
_destroyed = new SimpleClip("gamedata/17226_meatball4u_explode4.wav");
(...)
These sounds all come from Freesound, except for "wuw1.wav" that I generated using a free program called maXwave.
Now we want to play these sounds. We modify MyGame to play "_destroyed" when the player dies. As you can see, all we need to do is add a call to play():
/** main game loop **/
public void playLevel() {
(...)
collision =CollisionDetection.findCollisionListSlow(_enemyBullets,_shipList);
if (null!=collision && !collision._a.isEmpty()) {
System.out.println("Boom! You died");
// done with the level
_destroyed.play();
return;
}
}
The "_boom" sound should play when an enemy dies, so we modify the Enemy class.
public class Enemy extends VisibleObject {
(...)
/** called when hit; returns true if the enemy should die **/
public boolean hitKills() {
_life--;
if (_life==0) {
// die
_world._boom.play();
_alive = false;
}
return !_alive;
}
}
And finally the "_fire" should should play when we fire, so we modify the Ship class:
public class Ship extends VisibleObject {
(...)
public void fire() {
_main._fire.play();
_main._bullets.add( new Bullet(this) );
}
}
And that's it! Now when we play the game we'll notice that there is sound when we fire, kill enemies, or are killed. The next step is to add explosions.
Next: 10 - Explosions