Tuesday, April 5, 2011

Flash Game Dev Tip #8 – Building a Shoot-em-up Part 3 – Return Fire

Flash Game Dev Tip #8 – Building a Shoot-em-up Part 3 – Return Fire:

Flash Game Dev Tips logo

Tip #8 – Flixel – Building a Shoot-em-up, Part 3 – Return Fire

This tip follows-on from Tip #4, where we added enemies and explosions into our game. But it was a little one-sided. This time the enemy are going to shoot back. And you’ll feel it, by way of a health bar and set of lives in our new HUD. Finally we’ll drop in the scrolling tile-map background and simple menu / game-over states. By the end it will look like this:

Scrolling tile-map background and simple menu and game-over states

Note: I’ve embedded the game at the bottom of the tip.

Return Fire

Last time we added the Enemy Manager, which spawned a regular supply of enemies at us. Each enemy had a launch function which set it moving. Let’s add the ability to fire to that:

// Will they shoot at the player? 70% chance of doing so
if (FlxMath.chanceRoll(70))
{
 willFire = true;
 fireTime = new FlxDelay(1000 + int(Math.random() * 500));
 fireTime.start();
}

This uses a new FlxMath function chanceRoll. The enemy has a 70% chance of firing at you. If this happens we create a new FlxDelay Timer of 1 second + up to an extra 0.5 second, and start it running.

Then in the Enemy update function we check that timer:

if (willFire && fireTime.hasExpired)
{
 Registry.enemyBullets.fire(x, y);
 willFire = false;
}

As you can see, this is calling the fire function in our Enemy Bullet Manager, passing in the x/y coordinates of the Enemy, which launches a bullet from the bullet pool:

public function fire(bx:int, by:int):void
{
 x = bx;
 y = by;
 FlxVelocity.moveTowardsObject(this, Registry.player, speed);
 exists = true;
}

FlxVelocity tells the bullet (this) to move towards the player at the value of speed (which in our case is 240 pixels per second).

Pixel Perfect Collision

If you are unlucky enough to be hit by our new enemy bullets then we need to damage your health.

Previously the game used native flixel collision, which is based on bounding-boxes (i.e. the rectangle that encloses your sprite). This isn’t desirable in a shoot-em-up. It meant the player could get shot without the enemy bullet even visually touching him. To address this we simply add one check into our bulletHitPlayer function [...]

No comments:

Post a Comment