vendredi 10 juin 2016

Movement not working AS3

I'm currently working on a game and am fairly new to as3. I'm stuck on the character movement i was following a guide and ended up with this as my code. when i test the game it just plays the character animation and i cant control it.

    package {

    import flash.display.Stage;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
    import flash.utils.Proxy;
    import flash.utils.flash_proxy;

    dynamic public class KeyObject extends Proxy {

        private static var stage:Stage;
        private static var keysDown:Object;

        public function KeyObject(stage:Stage) {
            construct(stage);
        }

        public function construct(stage:Stage):void {
            KeyObject.stage = stage;
            keysDown = new Object();
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
            stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
        }

        flash_proxy override function getProperty(name:*):* {
            return (name in Keyboard) ? Keyboard[name] : -1;
        }

        public function isDown(keyCode:uint):Boolean {
            return Boolean(keyCode in keysDown);
        }

        public function deconstruct():void {
            stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
            stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
            keysDown = new Object();
            KeyObject.stage = null;
        }

        private function keyPressed(evt:KeyboardEvent):void {
            keysDown[evt.keyCode] = true;
        }

        private function keyReleased(evt:KeyboardEvent):void {
            delete keysDown[evt.keyCode];
        }
    }
}
package  {
    import flash.display.Sprite
    import flash.events.Event;
    import KeyObject;
    public class Main extends Sprite{
        private var key:KeyObject;

        public function Main() {
            addEventListener(Event.ADDED_TO_STAGE,setupKeyObject);
        }

        function setupKeyObject(e:Event){
            key = new KeyObject(stage);
            stage.addEventListener(Event.ENTER_FRAME,movePlayer);
        }

        function movePlayer(e:Event){
            if(key.isDown(key.LEFT)){
               roy.x -= 5;
               }
            if(key.isDown(key.RIGHT)){
               roy.x +=5;
               }              
            if(roy.x<0){
                roy.x = 0;
            }
            if(roy.x > (stage.stageWidth - player.width)){
                roy.x = stage.stageWidth - player.width;
            }
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire