Flash扩展了多个类

时间:2014-05-30 22:30:44

标签: flash events inheritance extends

我遇到了一个问题,因为我需要扩展MovieClip和EventDispatcher以捕获事件。但我不知道该怎么做。

这是我的班级:

package 
{
    import flash.display.MovieClip;
    import flash.events.*;

    public class Character extends MovieClip //need to extend EventDispatcher as well
    {   

        addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
        addEventListener(KeyboardEvent.KEY_UP, onKeyUp);                
    var PressedKeys:Array = new Array();
        public function update()
        {
              //.....
        }

        private function onKeyDown(event:KeyboardEvent):void
        {
            PressedKeys[event.keyCode] = true;
            trace("Keycode: " + event.keyCode + " is: " + PressedKeys[event.keyCode]);
        }

        private function onKeyUp(event:KeyboardEvent):void
        {
            PressedKeys[event.keyCode] = false;
            trace("Keycode: " + event.keyCode + " is: " + PressedKeys[event.keyCode]);
        }

    }
}

3 个答案:

答案 0 :(得分:1)

由于您尚未将代码放在函数中,因此不会执行添加事件侦听器。

尝试将您的事件侦听器添加到类构造函数中:

package 
{
    import flash.display.MovieClip;
    import flash.events.*;

    public class Character extends MovieClip //need to extend EventDispatcher as well
    {   
        private var PressedKeys:Array = new Array();

        public function Character()
        {
            addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
            addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
        }

        public function update()
        {
            //.....
        }

        private function onKeyDown(event:KeyboardEvent):void
        {
            PressedKeys[event.keyCode] = true;
            trace("Keycode: " + event.keyCode + " is: " + PressedKeys[event.keyCode]);
        }

        private function onKeyUp(event:KeyboardEvent):void
        {
            PressedKeys[event.keyCode] = false;
            trace("Keycode: " + event.keyCode + " is: " + PressedKeys[event.keyCode]);
        }
    }
}

ActionScript没有多重继承 - 只有基类的单一继承。

但是,MovieClip已经扩展了EventDispatcher

答案 1 :(得分:0)

您实际上无法在AS3中扩展多个类,但MovieClip已经从EventDispatcher继承,因此在这种情况下不应该成为问题。

如果你发现你的事件听众没有触发,可能是因为你的MovieClip没有焦点。要全局侦听键盘事件,您只需要将侦听器添加到Stage

答案 2 :(得分:0)

您正在将听众添加到课程范围之外,因此即使他们不会产生错误,他们也没有任何效果,因为他们甚至没有指向该课程的实例。