2015-03-24 57 views
1

對於問題的目的,想象一下,我有一個對象在舞臺上。當我點擊另一個按鈕時,我希望顏色改變1秒,然後在完成時再次恢復。AS3在按鈕(或任何事件)事件後運行事件一段時間的事件

這裏是我的演示代碼如下所示:

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; 
} 

什麼,我想是某種形式的定時器功能在上面的功能被合併。我不知道該怎麼做,因此爲什麼沒有實現。

回答

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

爲了進一步解釋Timer類上面使用:創建一個新的計時器

myTimer=new Timer(1000,1) 

括號中的第一個數字是你想要的計時器爲運行的毫秒數時

(如1000 = 1秒) 第二個數字是您希望計時器重複的次數(或0代表無限重複)。

每當計時器達到您輸入的時間(1000),這將觸發事件Timer_Event.TIMER的任何事件監聽器,例如,如果您想讓它改變顏色的開和關,您可以有多個重複計時器並更改功能。

其他有用的東西定時器可以這樣做:

您可以

Timer_Event.TIMER_COMPLETE  

添加事件偵聽器(熄滅時,所有重複完成)

myTimer.currentCount 

將返回的數量重複計時器迄今已完成。

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 
    ); 

} 

希望能有所幫助。