Tuesday, April 15, 2008

Tweener for games: Countdown

Last week I came back from holidays, I was back in my home country after almost 6 years since I left, that's why I couldn't update the blog...
Anyway, as mentioned before, I'll be writing some tutorials on how to use Tweener for games development, however, take into account that the code can be used on other applications as well...
The first "tutorial" is

Creating a countdown using Tweener

From my point of view, adding a countdown to a game helps to improve the playability as the user feels more challenged to finish certain task.
After reading Arthur Debert's Tweener Tips, I got the idea on developing further his "Poor's man timer":

Tweener.addTween(this, {time:0.3, onComplete: myFunction});

Right, so if we put it into a function, then we have:


var timeleft : Number = 30;

function tweenDown() : Void
{
trace(timeleft);
timeleft--;
Tweener.addTween(this, {time:1, onComplete:tweenDown});
}

tweenDown();


First we declare a variable called "timeleft" and set it to 30, so we will count down from 30 seconds to 0.
The function tweenDown() traces the updated "timeleft", decreases the timeleft value by one and using tweener it calls itself every second thanks to the onComplete parameter.

If we tide up a bit, we can add another function to trace the updated value of timeleft, then we have something like:

var timeleft : Number = 30;

function showTimeleft() : Void
{
trace(timeleft);
}

function tweenDown() : Void
{
timeleft--;
Tweener.addTween(this, {time:1, onUpdate:showTimeleft, onComplete:tweenDown});
}

tweenDown();


The function showTimeLeft() will trace the updated value of timeleft thanks to the parameter onUpdate and this allow us to do something else instead of only tracing; we can add a textfield (with instance name txtTime) to show us the updated timeleft value and the updated script would be:

var timeleft : Number = 30;

function showTimeleft() : Number
{
return txtTime.text = timeleft;
}

function tweenDown() : Void
{
Tweener.addTween(this, {time:1, onUpdate:showTimeleft, onComplete:tweenDown});
}
tweenDown();


Now, the problem is that when the countdown reaches 0, it doesn't stop!
so we can add another function to check if there's any "timeleft" and if there isn't, then do something else. The final script for a simple countdown is:

import caurina.transitions.Tweener;

var timeleft : Number = 30;

function showTimeleft() : Number
{
return txtTime.text = timeleft;
}

function tweenDown() : Void
{
Tweener.addTween(this, {time:1, onUpdate:showTimeleft, onComplete:countDown});
}

function countDown() : Void
{
if(timeleft > 0){
timeleft--;
tweenDown();
} else {
trace("GAME OVER!");
Tweener.removeAllTweens();
}
}

tweenDown();


and this is the example:




Salut!

No comments: