Friday, 2 October 2015

Sprite Collisions - Simplegamelib Part Two

This is the second part in an ongoing series where we will look a Dart package I am developing for simple Canvas based sprites games. I have written a couple of little games in Dart and always thought it would be an idea to split off all the general code into a reusable package.

The library is called simplegamelib and is heavily inspired by PyGame. The source is on GitHub here and the package is on pub. My personal aims are to write a Space Invaders type game and have really understandable library so it can be used to learn Dart. The code (so far!) is on GitHub and the project's homepage is here on blogger.

This time we will create a simple scene and again have a familiar looking sprite move from one side of the screen to the other. This time they will bump into another ninja so we add another sprite.

void main() {
  Game game = new Game("My Game", '#surface');

  player = game.createSprite("images/ninjadude.png");

  player
    ..position = new Point(0, 10)
    ..movement = Movements.east;

  dude = game.createSprite("images/ninjadude.png");

  dude..position = new Point(200, 20);

  dude.height = 48;
  dude.width = 48;
  player.height = 48;
  player.width = 48;

  game.customUpdate = collisionDemo;

  print('starting game...');

  game.start();
}

// Custom detection routine.
void collisionDemo() {
  document.body.style.backgroundColor =
      player.detectCollision(dude) ?  "#ffcc00" : "cornflowerblue";
  if (player.x > 333) {
    player.x = -50;
  }
}

This time around we create another sprite and both are set to a width and height of 48 pixels. This area for each ninja is used to detect whether they overlap. This type of collision detection can be used in all sorts of games. We take advantage of a hook in the Game object customUpdate that is called after each update. Here we can check if the two sprites collide and change the colour of the page accordingly. If the moving player sprite goes out of view it is set back to just off screen on the left. Click here to see it in action.

Next time, we will look at Sprite drawing priority!