Tuesday, October 26, 2010

Create a nice score displaying effect using AS3

Today we will create a nice score displaying effect in AS3.

In some games when you get a portion of money, you see them being added to your score display in little bits, like a time counter. I've made an example below. Try setting the amount of score you want to reach in the input field and hitting the change button, you'll see that it will increase by little bits. Try making a bigger interval (for example, going from 60000 to 100).


Now, how I coded this.

var realNumber:Number = 25238;
addZeros();

setInterval(updateDisplayedScore, 10);
var displayedNumber:Number = 0;

function updateDisplayedScore():void
{
if ((displayedNumber+100)<realNumber)
{
displayedNumber +=  100;
}
else if ((displayedNumber-100)>realNumber)
{
displayedNumber -=  100;
}
else if ((displayedNumber)<realNumber)
{
displayedNumber++;
}
else if ((displayedNumber)>realNumber)
{
displayedNumber--;
}
addZeros();
}

function addZeros():void
{
var str:String = displayedNumber.toString();
scoreDisplay.text = "$";
// scoreDisplay - name of text field on screen
for (var i=0; i < (6 - str.length); i++)
{
scoreDisplay.appendText("0");
}
scoreDisplay.appendText(str);
}

First of all we create a function to add zeros in the beginning of the score - addZeros(). This function will check, if zeros are needed to be added in front of the displayed score.

Secondly, we set up an interval that we call every 10 milliseconds and update the score with a function updateDisplayedScore. We have 2 variables - one is realNumber, which is the number that represents the score, and the second is displayedNumber, which is the number we're updating. In the updateDisplayedScore function, we check if displayedNumber is more (less) than realNumber by more than 100, and if it is - we decrease (increase) it by 100. Then if the interval is less than 100, we add or remove 1 from the number.

Hope this was helpful, thanks for reading!

No comments:

Post a Comment