0

我是 Actionscript 3 的新手,我希望使用键盘上的向下箭头允许一个圆圈向下移动。这是我的代码:

package  {

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

public class Circle extends MovieClip {

    public function Circle() {
        // constructor code
        var speed:int = 3;

        addEventListener(KeyboardEvent.KEY_DOWN,keyIsDown);

        function keyIsDown(event:KeyboardEvent) {
            if(event.keyCode == Keyboard.DOWN) {
                y = y+=speed;
            }
        }
    }

}

}

当我测试它时,当我按下向下键时没有任何反应。有人知道代码有什么问题吗?

4

1 回答 1

2

尝试将键盘事件添加到舞台而不是类。此外,我不会嵌套这样的函数,一般来说是不好的做法。这条线y = y+=speed;也令人困惑,不应该是y += speed;吗?

编辑:对不起,我猜阶段在构造函数中将为空,我添加了一个 ADDED 事件侦听器。

尝试这个:

package  {

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

    public class Circle extends MovieClip {

        public function Circle() {
            // constructor code
            var speed:int = 3;

            addEventListener(Event.ADDED, onAdded);        
        }

        private function onAdded(event:Event) {
            stage.addEventListener(KeyboardEvent.KEY_DOWN,keyIsDown);
        }

        private function keyIsDown(event:KeyboardEvent) {
            if(event.keyCode == Keyboard.DOWN) {
                 y += speed;
            }
        }

    }
}
于 2012-06-29T17:21:47.000 回答