Saturday, 10 October 2015

Background and Sound - Simplegamelib Part Five

This is the fifth part in an ongoing series where we will look at the package I am currently writing called simplegamelib. Development is usually a little ahead of the current blog post. The projects homepage is located here.

This demo is our most complicated so far. First change is that the white background is replaced by an image. The ninja will still be movable via the cursor keys but will be able to pick up the collectible hearts (ninja's need love too!) which emit a little sound when collected.

To set the background, the Renderer must be told of the image to be used. The Audiobank class loads a mp3 file which is given the name 'test' which is used to request that sound to play later on. Three heart sprites are created and added to the collectables list in the Game object. In the update method, the player is checked for collision with any of the hearts. If there is a collision, the heart is set to alive = false, the SpriteGroup is cleared of dead entries and the sound is played.

Remember Dartium does not play MP3 files so run from another browser!

Sprite player;
AudioBank sounds = new AudioBank();
Game game = new Game("My Game", '#surface');

void main() {

  sounds.load('test', 'sounds/coin.mp3');
  player = game.createSprite('images/ninjadude.png');
  game.player.sprite = player;
  game.renderer.liveBackground.setImageBackground('images/background.png');

  for (int i = 0; i < 3; i++) {
    Sprite heart = new Sprite.fromFilename('images/heart.png');
    heart
      ..position = new Point(100 + (i * 75), 100)
      ..width = 24
      ..height = 24;
    heart.updatePos();
    game.collectablesGroup.add(heart);
  }

  player
    ..position = new Point(0, 30)
    ..movement = new Point(0, 0)
    ..width = 48
    ..height = 48;

  game.customUpdate = soundDemo;

  print('starting game...');
  game.setUpKeys();
  game.start();
}

void soundDemo() {
  List pickedHearts = game.collectablesGroup.detectCollision(player);

  pickedHearts.forEach((Sprite heart) {
    heart.alive = false;
    game.collectablesGroup.removeDead();
    sounds.play("test");
  });
}

Click here to see it in action.

Next time, we will look behind the scenes at the unit testing for this package!