How do I get my movieclip character to move?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 11:27:54

问题


I've been trying for a few hours now and I cant get my little character to move with the keyboard.

I have ran a trace to make see if anything was happening and the position value does change but my character doesn't react to that position change.

I receive no errors. Both my Character and BrickBlock are movieclips and they have been imported for ActionScript.

If any other information is needed please let me know. Thank you! :)

My following code:

package  {

import flash.events.Event
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;

public class CharMove extends MovieClip {

    var char1 :Character;
    var block :BrickBlock;

    public function CharMove() 
    {           
        char1 = new Character();
        block = new BrickBlock();

        //this.addEventListener(Event.ENTER_FRAME, collide)
        stage.addEventListener(KeyboardEvent.KEY_DOWN, kDown);
    }

    /*function collide(e:Event):void
    {
            if(char.hitTestObject(block))
            {
                char.visible = !char.visible;
            }
    }*/

    function kDown(event:KeyboardEvent):void
    {
        switch (event.keyCode)
        {
            case Keyboard.LEFT:
                char1.x -= 5;
                trace(char1.x);
                break;

            case Keyboard.RIGHT:
                char1.x +=5;
                trace(char1.x);
                break;
        }
    }

}

}


回答1:


You might want to consider writing a static Input class.

package input {
    import flash.display.Stage;
    import flash.events.KeyboardEvent;

    public class Input {

        private static var keys:Array = new Array(255);

        public static function setup(stage:Stage):void {
            stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyDown);
            stage.addEventListener(KeyboardEvent.KEY_UP, KeyUp);
        }

        private static function keyDown(e:KeyboardEvent):void {
            keys[e.keyCode] = true;
        }

        private static function keyUp(e:KeyboardEvent):void {
            keys[e.keyCode] = false;
        }

        public static function isKeyDown(k:int):Boolean {
            return keys[k];
        }

        public static const A:uint = 65;
        public static const B:uint = 66;
        public static const C:uint = 67;
        // The rest of the keys...
    }
}

To use it first call setup() which adds the listeners for KEY_DOWN and KEY_UP events. They you can easily query keys and do relevant actions accordingly.

Input.setup(stage);

/...

if(Input.isKeyDown(Input.A)) {
    char1.x -= 5;
}


来源:https://stackoverflow.com/questions/26533054/how-do-i-get-my-movieclip-character-to-move

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!