Saturday, March 5, 2011

Flash Game Dev Tip #4 – Bullet Manager Part 2

Flash Game Dev Tip #4 – Bullet Manager Part 2: "

Flash Game Dev Tip #4

Tip #4 – Flixel – Bullet Manager Part 2

This tip follows-on from Tip #3, where we got a player controlled space-ship up, and had it fire all kinds of bullet death. In this tip we’re going to add something to use those bullets on – an Enemy manager, and a particle effect for when they are shot. By the end it’ll look like this:

Bullet manager demo-2

Enemy Manager

As with the bullets in the previous tip we are going to create an Enemy Manager. This class will be responsible for creating a pool of enemies, launching them and recycling them when killed.


package
{
 import org.flixel.*;
 import flash.utils.getTimer;

 public class EnemyManager extends FlxGroup
 {
  private var lastReleased:int;
  private var releaseRate:int = 500;

  public function EnemyManager()
  {
   super();

   for (var i:int = 0; i < 100; i++)
   {
    add(new Enemy);
   }
  }

  public function release():void
  {
   var enemy:Enemy = Enemy(getFirstAvail());

   if (enemy)
   {
    enemy.launch();
   }
  }

  override public function update():void
  {
   super.update();

   if (getTimer() > lastReleased + releaseRate)
   {
    lastReleased = getTimer();

    release();
   }
  }

  public function bulletHitEnemy(bullet:FlxObject, enemy:FlxObject):void
  {
   bullet.kill();

   enemy.hurt(1);

   Registry.fx.explodeBlock(enemy.x, enemy.y);

   FlxG.score += 1;
  }

 }

}

Our Enemy Manager works identically to the Bullet Manager from before. It starts by creating a pool of 100 enemies, which I admit is probably 90 more than we actually need at this stage of the game! Enemies are just extensions of an FlxSprite, and by default they have their exists value set to false, so they are free for allocation by the manager.

The manager overrides the flixel update function. All we do in there is check the value of the timer. getTimer() is a Flash utility class that gives you the number of milliseconds since the SWF started playing. It’s a really good way of timing things without having to use Timer Events, as it’s just integer based, fast and pretty accurate.

Our releaseRate is set to 500. That’s in milliseconds, so 500 would be every half a second (1000 ms per second). If enough time has elapsed we release a new enemy. This simply pull the next available enemy from the pool and call its launch function.

The enemy class looks like this [...]

No comments:

Post a Comment