Keyboard lag

hello as3!

this is my main class:


package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
 
    public class main extends Sprite
    {
        public var mc1:Sprite;
        public var dy = 0;
        public var dx = 0;
  
        public function main()
        {
            stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDown );
            stage.addEventListener( "enterFrame", _onEnterFrame);
            mc1 = new disc();
            this.addChild(mc1);
            mc1.y=stage.stageHeight/2;
   
        }
        private function keyDown( event:KeyboardEvent ) : void
        {
            trace(event.keyCode);
            var code = event.keyCode;
            if(code=="39")
            {
            trace("ad");
            dx+=3;
            }
            else if(code=="37")
            {
            trace("ad");
            dx-=3;
            }
            if(code=="38")
            {
            trace("ad");
             dy-=3;
             }
        }
        private function _onEnterFrame(e:Event) : void
       {
             dy+=0.1;
             mc1.y+=dy;
             mc1.x+=dx;
        }
    }
}

so, i got a mc1 clip onStage (instance of “disc”) and it roams around with the key buttons.

It all works fine but it has a lot of lag… what’s wrong? my pc is fast indeed…

thank you.

try removing all the trace statements

done it, didnt solve it.

I heard KeyListners were the cause of this lag… is it true? what is the alternative?

Just a tip for optimising your code; use the most minimalist display object that does what you want it to.
If all your doing is drawing in a display object then make it a Shape instead.

i used a simple shape, a square, and it is still lagging.

Isnt there another way to do this?

when ever i would make games i would put all movements in a big enter frame, and the keypress just switched vars on and off, that way the little delay never happened, but yeah, it’s a weird problem…

add the enter frame event listener to your clip rather than your stage…

The problem is that the key listener gets events the same way that a word program does. Try pressing a letter and notice there is a moment before it repeats. To fix this have to change the player coordinates on the enterFrame event.

thx, I got it… its a windows problem, not flash.

Its realy usefull in word though…

I find this class works a treat:

http://flashgamecode.net/classes/key-polling-class