0

我有当前的代码:

enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();

如何更改计时器,而不是sendEnemy每 2 秒触发一次,而是在 1 到 3 秒之间的随机时间触发它?

4

4 回答 4

3

该类Timer具有delay指示两个“计时器”事件之间的延迟的属性。因此,您只需在 sendEnemy 开始时随机更改延迟(下一次生成)。

function sendEnemy(evt:TimerEvent):void {
  Timer(evt.currentTarget).delay = (1+Math.random()*2)*1000; // change the delay until the next call.

  // continue with the usual sendEnemy code.
}
于 2013-05-22T13:42:45.270 回答
1

在 1 到 3 秒之间触发,意味着每秒有 33% 的几率被触发。所以:

enemyShipTimer = new Timer( 1000 );
enemyShipTimer.addEventListener("timer", function( e:TimerEvent ):void
{
    if( Math.random() < 0.33 )
    {
        trace( "triggered!" );
    }
});
enemyShipTimer.start();
于 2013-05-22T13:40:12.223 回答
1
package 
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;

public class Test extends MovieClip {
    private var _timer:Timer = null;
    public function Test() : void {
        addEventListener(Event.ADDED_TO_STAGE, _Init);
    }

    private function _Init(e:Event) : void {
        _RandomTimer();
    }

    private function _RandomCount() : Number {
        var min = 1000;
        var max = 2000;
        return Math.floor(Math.random() * max + min);
    }

    private function _RandomTimer() : void {
        _timer = new Timer(_RandomCount(), 1);
        _timer.addEventListener(TimerEvent.TIMER, _OnTimerCall);
        _timer.addEventListener(TimerEvent.TIMER_COMPLETE, _OnTimerEnd);
        _timer.start();
    }

    private function _OnTimerCall(e:TimerEvent) : void {
        trace(_timer.delay);
    }

    private function _OnTimerEnd(e:TimerEvent) : void {
        _timer.removeEventListener(TimerEvent.TIMER_COMPLETE, _OnTimerEnd);
        _RandomTimer();
    }
}
}
于 2013-05-22T13:46:49.717 回答
0

您可以使用该Math.random功能。您可以通过乘以选择随机函数的最大值。但是你的随机数仍然会归零,所以你必须加上一个起始数字。

var randomNumber:Number = Math.random(); // Number between 0 - 1
randomNumber *= 2000; // Number between 0 - 2000
randomNumber += 1000; // Number between 1000 - 3000

enemyShipTimer = new Timer(randomNumber);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
于 2013-05-22T13:35:00.110 回答