How to Make a Vertical Shooter in AS3 – Part 5

Part 5: Scoring

Now that we’ve got the hardest part down, it all gets easier from here. This chapter will be simple, just some code that has scoring. Also, as promised, we’re going to have a function run when the player is hit by an enemy. Let’s start with this one first, eh?

In order to do this, we have to make a frame called “lose”. This will be the frame that we’ll navigate to when we get hit. It’ll be simple, just some text that says “You Lose” and a listener for keystrokes or a click that will return us to play another game. First, make the frame called “lose”. I recommend making an entire new layer for labels, but this isn’t required. In that frame, draw or type in whatever you want to signify that the player has lost the game. I’m just going to put the text, “YOU LOSE”.

Then, in the actions, type in the following code:

stop();

stage.addEventListener(MouseEvent.CLICK, goBack);

function goBack(event:MouseEvent):void{
	gotoAndStop(1);
	stage.removeEventListener(MouseEvent.CLICK, goBack);
}

Then, we’ll have to add a variable called gameOver to signify that the game is over and that some stuff should be deleted and such.

//whether or not the game is over
var gameOver:Boolean = false;

Then, both in the Bullet‘s and the Enemy‘s eFrame() function, add the following code:

//checking if game is over
if(_root.gameOver){
	removeEventListener(Event.ENTER_FRAME, eFrame);
	this.parent.removeChild(this);
}

Finally, add this code to where we hit tested for the main character in “Enemy.as”

//hit testing with the user
if(hitTestObject(_root.mcMain)){
	//losing the game
	_root.gameOver = true;
	_root.gotoAndStop('lose');
}

If you test the game, there will be a bug that comes up. Don’t worry, we can fix it. Just keep mcMain in the “lose” frame. Also, so it can’t be controlled while in the “lose” frame, place the following code:

//keeping mcMain out of sight
mcMain.x = stage.stageWidth;
mcMain.y = stage.stageHeight;
mcMain.removeEventListener(Event.ENTER_FRAME, moveChar);

Phew, that was a lot of work, wasn’t it? Now we can move onto actually scoring the game. First, we have to define a score variable at the top:

//the player's score
var score:int = 0;

Then, increment the score every time an enemy is killed. Place this code in the Enemy’s hit testing for the bullet.

//up the score
_root.score += 5;

Now, we can show the score to the user with a dynamic text field. Make one at the bottom of the stage and give it an instance name of txtScore. Next, place this code into the moveChar function.

//updating the score text
txtScore.text = 'Score: '+score;

Pretty easy, right? Well, that’s all we’re going to do for scoring. Next, we’ll add some sweet finishing touches, eh?

Preview

Download Source
(Requires Flash CS3 or above)

Subscribe!

Subscribe!
Enter your email address:  

Awesome Tutorials