AS3在按钮(或任何)事件之后运行事件一段时间

时间:2015-03-24 23:32:29

标签: actionscript-3

出于问题的目的,想象一下我在舞台上有一个对象。当我点击另一个按钮时,我希望颜色改变1秒钟,然后在完成时再次恢复。

这是我的演示代码:

Button.addEventListener(MouseEvent.CLICK, Colour_Change);

function Colour_Change(evt: MouseEvent): void {
    var my_color: ColorTransform = new ColorTransform();
    my_color.color = 0xFF0000;
    Coloured_Object.transform.colorTransform = my_color;
}

我想要的是将某种计时器功能纳入上述功能。我不知道该怎么做,所以为什么没有实现。

3 个答案:

答案 0 :(得分:1)

您应该使用flash.utils.Timer类。
Adobe ActionScript 3.0 Reference for the Timer class

以下内容足以让您朝着正确的方向前进:

import flash.utils.Timer;

var myTimer:Timer = new Timer(1000, 1); // 1 second
var running:Boolean = false;

Button.addEventListener(MouseEvent.CLICK, Colour_Change);
myTimer.addEventListener(TimerEvent.TIMER, runOnce);

function Colour_Change(evt: MouseEvent): void {
    var my_color: ColorTransform = new ColorTransform();
    my_color.color = 0xFF0000;
    Coloured_Object.transform.colorTransform = my_color;
    if(!running) {
        myTimer.start();
        running = true;
    }
}

function runOnce(event:TimerEvent):void {
    // code to revert the button's color back goes here

    myTimer.reset();
    running = false;
}

如果您需要更多帮助,或者如果此示例有错误,请通过此答案的评论部分告诉我。

答案 1 :(得分:1)

进一步解释上面使用的Timer类:

创建新计时器时

myTimer=new Timer(1000,1)

括号中的第一个数字是您希望计时器运行的毫秒数(例如1000 = 1秒) 第二个数字是您希望计时器重复的次数(或0表示无限次重复)。

每次计时器到达你输入的时间(1000),这将触发事件Timer_Event.TIMER的任何事件监听器,所以例如如果你想让它改变颜色的开启和关闭,你可以有多次重复在计时器上并更改功能。

计时器可以做的其他有用的事情:

您可以为

添加事件侦听器
Timer_Event.TIMER_COMPLETE     

(所有重复完成后熄灭)

myTimer.currentCount

将返回计时器到目前为止所执行的重复次数。

答案 2 :(得分:0)

为此,您可以像其他答案所说的那样使用Timer对象或setTimeout()函数,如下所示:

// the current color of our target object
var default_color:ColorTransform;
// the delay in milliseconds
var delay:int = 1000; 

btn.addEventListener(MouseEvent.CLICK, Colour_Change);
function Colour_Change(evt: MouseEvent): void {

    // save the current color of our target object
    default_color = target.transform.colorTransform;

    var new_color:ColorTransform = new ColorTransform();
        new_color.color = 0xFF0000;

    target.transform.colorTransform = new_color;

    var timer:Timer = new Timer(delay, 1);
        timer.addEventListener(TimerEvent.TIMER, function(e:TimerEvent):void {
            // after the delay, we use the default color of our target
            target.transform.colorTransform = default_color;
        })
        timer.start();

    // using setTimeout(), you have to disable this if using the Timer
    var timeout:int = setTimeout(
        function(){
            clearTimeout(timeout);
            // after the delay, we use the default color of our target
            target.transform.colorTransform = default_color;
        }, 
        delay
    );

}

希望可以提供帮助。