Friday, 6 November 2015

Sprite Lifecycle - Simplegamelib Part Ten

This is the tenth 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.

Ninjas have a tough life and often have a lot thrown at them at once. This sometimes involves painful objects. In a game, we need to check how each object is interacting with others in the game world. The projectiles will be in the SpriteGroup. Sadly these will cause the Ninja to die but we don't want the character just to suddenly vanish. We want a skeleton to appear (or an explosion in a game set in space). This is why the Sprite has both an alive property and a dying property.

import 'dart:html';
import 'package:simplegamelib/simplegamelib.dart';

Sprite player;
SpriteGroup fireballs = new SpriteGroup();
Game game = new Game("My Game", '#surface');

void main() {
  player = game.createSprite('images/ninjadude.png', 48, 48);
    ..cyclesToDie = 1000;
  for (int i = 0; i < 5; i++) {
    var fireball = game.createSprite('images/fire.png', 24, 24);
      ..movement = Movements.west
      ..x = 290 + i * 100
      ..y = 60
      ..speed = 3;

    ..player.sprite = player
    ..customUpdate = spriteDying;

    ..position = new Point(10, 30)
    ..movement = new Point(0, 0);

  print('starting game...');

void spriteDying() {
  if (player.dying) return;
  List collisions = fireballs.detectCollision(player);

  collisions.forEach((Sprite fireball) {
    fireball.alive = false;
    game.player.sprite.dying = true;

Next time, we will take a break and have a look at the Left-Right shoot-em-up I have been working on using simplegamelib!