Sunday, February 10, 2008

Actionscript 3.0 Timer and key events

package
{

import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.text.TextField;
import flash.utils.Timer;
import flash.events.TimerEvent;

public class BM2 extends Sprite
{

public var txtbox:TextField;

public var kDown:JS;
public var kUp:JS;
public var xx:int;
public var yy:int;
public var rep:Timer;
public var ymov:int;
public var xmov:int;
public function BM2()
{
kDown = new JS();
kUp = new JS();
txtbox = new TextField();
txtbox.text = "Hello World";


addChild(txtbox);


stage.addEventListener(KeyboardEvent.KEY_DOWN,keydownhandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyuphandler);
kDown[37] = function():void{xmov = -1;};
kDown[38] = function():void{ymov = -1;};
kDown[39] = function():void{xmov = 1;};
kDown[40] = function():void{ymov = 1;};
kUp[37] = function():void{xmov = 0;};
kUp[38] = function():void{ymov = 0;};
kUp[39] = function():void{xmov = 0;};
kUp[40] = function():void{ymov = 0;};

rep = new Timer(1,0);
rep.addEventListener(TimerEvent.TIMER, draw);
rep.start();


}
public function test(event:TimerEvent):void{txtbox.text = event.toString();}
public function draw(event:TimerEvent):void
{
xx = xx + 1 * xmov;
yy = yy + 1 * ymov;
graphics.clear();
graphics.lineStyle(1);
graphics.beginFill(0xFF8000);
graphics.drawCircle(xx, yy, 10);

}

public function keydownhandler(evento:KeyboardEvent):void
{
txtbox.text = evento.keyCode.toString() + " " + kDown[evento.keyCode];
if (evento.keyCode >= 37 && evento.keyCode <= 40) kDown[evento.keyCode]();

}
public function keyuphandler(evento:KeyboardEvent):void
{
txtbox.text = evento.keyCode.toString() + " " + kUp[evento.keyCode];
if (evento.keyCode >= 37 && evento.keyCode <= 40) kUp[evento.keyCode]();

}



}


} //end package


import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
import flash.geom.Rectangle;




//this is how i am rescuing the coolness of javascripts objects!!
dynamic class JS
{
public function JS(){}
}

1 comment:

Anonymous said...

Thanks for writing this.