In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

Keyboard Events demo

Flash version of http://lib.ivank.net/demos/kevents.html
Get Adobe Flash player
by Ivan_Kuckir 02 Sep 2012
    Embed
/**
 * Copyright Ivan_Kuckir ( http://wonderfl.net/user/Ivan_Kuckir )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/croI
 */

package 
{
    import flash.net.URLRequest;
    
    import flash.display.Sprite;
    import flash.display.Loader;
    
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    
    import flash.system.LoaderContext;
    
    public class Demo extends Sprite 
    {
        var s, car, angle = 0, speed = 0;
        var l, r, u, d;
        
        var context = new LoaderContext();
        
        public function Demo()
        {
            stage.frameRate = 60;
            context.checkPolicyFile = true;
            
            s = new Sprite();
            var ldr = new Loader();
            ldr.load(new URLRequest("http://lib.ivank.net/demos/asphalt.jpg"), context);
            ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e)
            {
                s.graphics.beginBitmapFill(e.target.content.bitmapData);
                s.graphics.drawRect(0,0,stage.stageWidth, stage.stageHeight);
            });
            stage.addChild(s);
            
            
            // car            
            car = new Sprite(); 
            car.x = stage.stageWidth/2;
            car.y = stage.stageHeight/2;
            var cb = new Loader();
            cb.load(new URLRequest("http://lib.ivank.net/demos/car.png"));
            cb.x = -123; cb.y = -50; car.addChild(cb);
            stage.addChild(car);
            
            // events
            stage.addEventListener(KeyboardEvent.KEY_DOWN, onKD);
            stage.addEventListener(KeyboardEvent.KEY_UP  , onKU);
            stage.addEventListener(Event.ENTER_FRAME     , onEF);
        }
        
        function onKD (e)
        { 
            if(e.keyCode == 37) l = true;
            if(e.keyCode == 38) u = true;
            if(e.keyCode == 39) r = true;
            if(e.keyCode == 40) d = true;
        }
        
        function onKU (e)
        {
            if(e.keyCode == 37) l = false;
            if(e.keyCode == 38) u = false;
            if(e.keyCode == 39) r = false;
            if(e.keyCode == 40) d = false;
        }
        
        function onEF (e)
        {
            speed *= 0.9;
            if(u) speed += 1+speed*0.06;
            if(d) speed -= 1;
            
            if(r) angle += speed * 0.003;
            if(l) angle -= speed * 0.003;
                
            car.rotation = angle*180/Math.PI;
            car.x += Math.cos(angle) * speed;
            car.y += Math.sin(angle) * speed;
        }
    }
}