Game Development Reference
In-Depth Information
Timers
It is one of the most useful objects in game development and Flash programming
makes it all very easy to set up. Basically, you create a timer object and tell it to call
your function often.
Let us add a timer to our previous sprite test example, and every time the timer is
fired, we will make the sprite move in a random direction. We will also take care to
check if the sprite is off the stage to reverse its course so that it stays on the stage,
that is, it is visible.
package {
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class SpriteTest extends Sprite
{
private const HEIGHT:int = 100;
private const WIDTH:int = 100;
private var m_sprite:Sprite;
private var m_timer:Timer;
private var m_dx:Number = 1;
private var m_dy:Number = 2;
public function SpriteTest()
{
m_sprite = new Sprite();
m_sprite.graphics.beginFill(0xFF0000);
m_sprite.graphics.drawCircle(0, 0, 3);
m_sprite.graphics.endFill();
m_sprite.x = 25;
m_sprite.y = 25;
addChild(m_sprite);
// Set up the timer and fire it
m_timer = new Timer(10, 0);
m_timer.addEventListener(TimerEvent.TIMER, onTimer);
m_timer.start();
}
private function onTimer(event:TimerEvent):void {
moveSprite();
}
private function moveSprite():void {
// Check the bounds for x
if ( m_sprite.x < 0 || m_sprite.x > WIDTH )
 
Search WWH ::




Custom Search