【发布时间】:2013-08-19 15:12:24
【问题描述】:
我有一个已添加到舞台的按钮。当它被创建时,它会移动到舞台的可见区域,并调用一个激活函数,该函数会为其添加一个事件侦听器来查找鼠标按下。但是,由于某种原因,这不起作用。关于为什么的任何想法?我已经尝试通过创建它的对象向对象添加一个侦听器,但这也不起作用。
package menus {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.*;
public class MenuPlayButton extends MovieClip {
private var _stageWidth, _stageHeight:int;
private var comeInTimer:Timer;
private var buttonSpeed:Number;
public function MenuPlayButton(stageWidth:int, stageHeight:int) {
_stageWidth = stageWidth;
_stageHeight = stageHeight;
alpha = 1;
rescaleMe();
repositionMe();
comeIntoMenu();
}
private function rescaleMe():void {
var oldWidth = this.width;
var oldHeight = this.height;
this.height = _stageHeight/10;
this.width = (this.height * oldWidth) / oldHeight;
}
private function repositionMe():void {
this.x = 0 - this.width;
this.y = _stageHeight * 0.56;
}
private function comeIntoMenu():void {
//Sets button's original speed
buttonSpeed = _stageHeight / 40;
//Adds timer that moves in the button
comeInTimer = new Timer(10,0);
comeInTimer.addEventListener(TimerEvent.TIMER, comeInTimerListener);
comeInTimer.start();
}
private function comeInTimerListener(e:TimerEvent):void {
if(x < 0) {
x += buttonSpeed;
buttonSpeed *= 0.93;
} else {
x = 0;
activate();
}
}
private function activate():void {
//Kills off timer
comeInTimer.removeEventListener(TimerEvent.TIMER, comeInTimerListener);
comeInTimer.stop();
comeInTimer = null;
this.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
trace("Button should be activated"); //This gets traced
}
function clicked(e:MouseEvent) {
trace("Button pressed");
}
}
}
【问题讨论】:
-
奇怪,我看不出这段代码有什么问题。考虑跟踪
this.stage、this.x和this.y以及Button should be activated,您的按钮可能由于在其创建过程中没有可用的阶段而处于关闭阶段。在这种情况下,将if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init);标准结构添加到构造函数中,并将其代码重定位到function init(e:Event=null):void {...}中,您可以在其中寻址阶段并检索其stageWidth和stageHeight属性而无需构造函数参数。 -
我尝试跟踪按钮,它给出了正确的结果。但是,当我尝试跟踪 Mouse.x 时,它给了我:menus\MenuPlayButton.as, Line 65 1120: Access of undefined property Mouse.
-
等一下...如果没有跟踪,当我导入 display.* 时代码可以工作,而不仅仅是 MovieClip! O_o
-
实际上,当我将侦听器添加到舞台时,它们会起作用,而不是按钮...
-
您是否将按钮添加到舞台?或者,也许您将其添加到其
visible为 false 或mouseChildren设置为 false 的容器中?这可以防止鼠标事件到达您的按钮。