MOUSE_DOWN 事件只触发一次。要获得您想要的效果,您需要 MOUSE_DOWN 和 MOUSE_UP 事件处理程序的组合。
您可以在 MOUSE_DOWN 事件中将变量设置为 true 以及来自的当前时间戳flash.utils.getTimer()
然后在 MOUSE_UP 上,如果您在 MOUSE_DOWN 中设置的变量为真,则计算经过的时间并相应地设置功率。
例子:
var isMouseDown:Boolean = false;
var mouseDownBegin:int;
var speed = 10;
var speed_inc = 2; // give it in per second
var speed_max = 100; // max speed possible
// add event handlers
myCannon.addEventListener(MouseEvent.MOUSE_DOWN, buttonPressed);
myCannon.addEventListener(MouseEvent.MOUSE_UP, buttonReleased);
function buttonPressed(event:MouseEvent){
isMouseDown = true;
mouseDownBegin = flash.utils.getTimer();
}
function buttonReleased(event:MouseEvent){
if(isMouseDown == true){
// get time between press and release
var timeElapsed = flash.utils.getTimer() - mouseDownBegin;
// reset isMouseDown
isMouseDown = false;
// compute speed
speed += int(Math.floor(speed_inc * (timeElapsed / 1000.0)));
speed = Math.min(speed, speed_max);
// code to fire ball with new speed
// .......
}
}
您还可以添加一个 ENTER_FRAME 事件并为功率计或其他东西设置动画以获得视觉效果
更新
正如 The_asMan 所指出的,MOUSE_UP
如果在舞台外拖动并释放鼠标,则不会触发事件。为了处理这种情况,为MOUSE_LEAVE
事件添加和事件侦听器,回调作为 buttonReleased 函数的副本,但它接受一个 Event 对象:
function buttonReleasedOutsideStage(event:Event){
if(isMouseDown == true){
// get time between press and release
var timeElapsed = flash.utils.getTimer() - mouseDownBegin;
// reset isMouseDown
isMouseDown = false;
// compute speed
speed += int(Math.floor(speed_inc * (timeElapsed / 1000.0)));
speed = Math.min(speed, speed_max);
// code to fire ball with new speed
// .......
}
}
stage.addEventListener(Event.MOUSE_LEAVE, buttonReleasedOutsideStage);