Thursday, September 2, 2010

Accuracy in a shooter game using AS3

In this tutorial, we will learn how to display player's accuracy in a shooter game.

Here is what we will achieve:

First of all, create a dynamic textfield on stage called stats and a Movie Clip with an instance name of target.

First part of the code creates necessary variables, counts hits and total shots fired and calls the function updateStats():

var shotsFired:Number = 0;
var hits:Number = 0;
var accuracy:Number = 0;

stage.addEventListener(MouseEvent.MOUSE_DOWN, shot);

function shot(MouseEvent):void

target.addEventListener(MouseEvent.MOUSE_DOWN, hitTarget);

function hitTarget(MouseEvent):void

Here is the function itself:

function updateStats()
 accuracy = (hits!=0)?(hits * 100 / shotsFired):(0);
 stats.text = "Shots fired: " + shotsFired + "\n";
 stats.appendText("Hits: " + hits + "\n");
 stats.appendText("Misses: " + (shotsFired - hits) + "\n");
 stats.appendText("Accuracy: " + accuracy.toFixed(2) + "%");


Here is the most important line:

accuracy = (hits!=0)?(hits * 100 / shotsFired):(0); - this is basically a short version of the if statement. Here is the syntax:


We need to check whether we have any hits. Because if we don't, accuracy will take value of NaN, so we will need to set it as 0% manually. If we do have hits, we set accuracy to this:

hits * 100 / shotsFired

It's a simple formula to find out the percentage of hits. Later, when we're adding accuracy to the text field, we use toFixed() method to round the accuracy to 2 decimal numbers.

Thanks for reading!

No comments:

Post a Comment