how to change boolean values with timerEvent in as3 - actionscript-3

I had written this small code to change a boolean value for 0 to 1 and vice versa every second
but it doesnt work.
The result is it always stays as 0. I must be making some stupid mistake. Please help. Thanks
var booleanL:Number = 0;
var myTimerL:Timer = new Timer(1000,60);
myTimerL.addEventListener(TimerEvent.TIMER, timerListenerL);
function timerListenerL (e:TimerEvent):void{
if(booleanL == 0) {
booleanL = 1;
} else if(booleanL == 1) {
booleanL = 0;
}
}
myTimerL.start();
trace(booleanL);

EDIT:
You can try using the computer clock time to make a stopwatch. The boolean will update every time the clock's end_time time is [delay] seconds higher than start_time. Delay is set by this line: delay = start_time.seconds + 2; here gives +2 seconds delay as limit before update
Try it like this...
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.events.TimerEvent;
import flash.events.Event; //added this for enter frame events
public class timer extends MovieClip
{
public var booleanL:int = 0;
public var start_time:Date = new Date;
public var end_time:Date = new Date;
public var delay:int;
public function timer()
{
//var myTimerL:Timer = new Timer(1000, 5);
//myTimerL.addEventListener(TimerEvent.TIMER, timerListenerL);
//myTimerL.start();
timer_Reset();
}
function timerListenerL ():void //(event:TimerEvent):void
{
trace("Am updating Boolean...");
if( 1 == booleanL)
{ booleanL = 0; trace(booleanL); }
else if (0 == booleanL)
{ booleanL = 1; trace(booleanL);}
}
//USE REAL TIME CLOCK VERSION
public function timer_Reset():void
{
start_time = new Date; //reset time to now..
delay = start_time.seconds + 2; //two seconds test delay
stage.addEventListener(Event.ENTER_FRAME, _update);
}
function _update (e:Event):void
{
//set end_time to now-time every frame,
//then check if end seconds are [+ delay] higher than start_time.seconds
end_time = new Date(); //set to Now time
if (end_time.seconds == delay)
{
trace(end_time.hours + ":" + end_time.minutes + ":" + end_time.seconds);
stage.removeEventListener(Event.ENTER_FRAME, _update);
timerListenerL (); //we update boolean via this function
timer_Reset(); //we reset for next check via this function
}
}
}

Related

AS3 timer works in game

I have a countdown timer I made in AS3 the start, stop, and reset works fine in the game.
Problem: This Flash app is now inserted into an external virtual-life game as some animated billboard/sign. Each "person" in the game sees the sign but must click the (Flash) button, inside the sign, to start the timer code. Only the person pressing button can see it working. Everyone is given 05:00 minutes to present their offer.
I need everyone in a room to see timer countdown since its for a auction.
Any help I would appreciate it.
This is what I tried to use so far:
package {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public class timerClass extends MovieClip
{
var myTimer:Timer = new Timer(1000, 300);
var i:Number = 300;
public function timerClass()
{
//# constructor code
timerTxt.text = String("05:00");
myTimer.addEventListener(TimerEvent.TIMER, updateTime);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, TimerComplete);
startbutton.addEventListener(MouseEvent.CLICK, StartNow);
pausebutton.addEventListener(MouseEvent.CLICK, PauseNow);
restartbutton.addEventListener(MouseEvent.CLICK, restartNow);
}
private function updateTime(e:TimerEvent)
{
i--;
var totalSeconds:* = i;
var minutes:* = Math.floor(totalSeconds/60);
var seconds:* = totalSeconds % 60;
if(String(minutes).length < 2)
{
minutes = "0" + minutes;
if(String(seconds).length < 2)
seconds = "0" + seconds;
}
timerTxt.text = minutes + ":" + seconds;
}
private function TimerComplete(e:TimerEvent)
{
messageTxt.text = "PRESENTATION IS NOW OVER"
timerTxt.text = String("00:00");
}
private function StartNow(e:MouseEvent)
{ myTimer.start(); }
private function PauseNow(e:MouseEvent)
{ myTimer.stop(); }
private function restartNow(e: MouseEvent): void
{
myTimer.stop();
myTimer = new Timer(1000, 300);
myTimer.addEventListener(TimerEvent.TIMER, updateTime);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, TimerComplete);
i = 300;
messageTxt.text = "";
timerTxt.text = String("05:00");
}
} //#end Class
} //#end Package
I need everyone in a room to see timer countdown since its for a auction
This is what timer should look like, I just need eveyone to see counter at same time once i press start.
https://cldup.com/cds0PwoS5Y.swf
thank you
jln

AS3: Why is a line created with .graphics appearing in two different places and when removed with parent.visible = false, only one goes?

Nobody seems to have this question already so I asked it because I've spent a few hours trying to debug this and can't find a solution;
Essentially, I have a function called draw, which is declared in my document class:
public function draw(Target: MovieClip,mX: int,mY: int,lX: int,lY: int):void {
Target.graphics.clear();
Target.graphics.lineStyle(1,0x000000,1);
Target.graphics.moveTo(mX,mY);
Target.graphics.lineTo(lX,lY);
}
I call it later to draw two lines, on two different MovieClips:
draw(Line,Line.mX,Line.mY,Mirror.x + (Mirror.width / 2),Line.lY);
draw(nextLine,(Mirror.x + (Mirror.width / 2)),200,(Mirror.x + (Mirror.width / 2)),0);
where
var Line: MovieClip = new MovieClip();
var Mirror: MovieClip = new mirror();
and Mirror is draggable, so Mirror.x changes whenever it is dragged.
Line is a line made using .graphics and Line.mX is equal to the Line.graphics.moveTo X value last time it was modified. Line.mY is the same, but for the Y coordinate. I set these values by doing this:
Line.mX = 0;
Line.mY = 200;
Line.lX = 550;
Line.lY = 200;
But with whatever values I want to draw the line, with lX and lY being equal to the X and Y coordinates of Line.graphics.lineTo. Then I draw Line using my draw function like this:
draw(Line,Line.mX,Line.mY,Line.lX,Line.lY);
Then it gets more complex because, actually, Line is just one line in an array of lines, created like this:
public var lines = [line0,line1,line2,line3,line4,line5,line6,line7,line8];
and each of those lines is created like this (with 0 being replaced by the line's number, respectively):
public var line0: MovieClip = new MovieClip();
then I give each line a number and a name, add them to the stage and hide them like this:
for each(var setupLine:MovieClip in lines) {
setupLine.num = (lines.indexOf(setupLine));
setupLine.name = ('line' + setupLine.num);
addChild(setupLine);
setupLine.visible = false;
}
Then, after making line0 visible, because I need to see it at the start, I loop through each line in a function that runs on ENTER_FRAME, and set the value of nextLine to a different value each time I run the loop like this:
for each(var Line:MovieClip in lines) {
nextLine = this['line' + (Line.num + 1)];
}
Within that loop, I then loop through a few other arrays, then check for a collision with the selected Line and another selected MovieClip from another array, which I wont go into or this question will be longer than the code for node.js.
So essentially, if the collision with the two MovieClips is present, I draw the line that I mentioned at the top of my question. But for some reason, although Line draws correctly, nextLine draws correctly, but a duplicate of it is drawn across the Y axis at 0, and stops where nextLine is on the Y axis (nextLine is vertical, so it has the same Y value at the start as at the end).
Even stranger, when I try to hide nextLine if the collision with the two MovieClips is no longer present, using this code:
nextLine.visible = false;
it only hides the version of nextLine that runs along the top of the stage, which I didn't even intend to create in the start.
EDIT
here is a link to the current source code
Here is a link to the entire project files with the original source code
copy/paste the new source code from the pastebin link to get the new version
Thanks in advance,
-Raph
I figured out how to do this, code is
package {
import flash.events.*;
import flash.utils.*;
import flash.display.*;
[SWF(backgroundColor="0xbdc3c7")]
public class LightStage extends MovieClip {
//import classes
public var globeClass:Globe = new Globe();
public var mirrorClass:Mirror = new Mirror();
public var lineClass:Line = new Line();
//create all stage objects
public var curLine:Line
public var nextLine:Line;
public var curMirror:Mirror;
//create containers
public var mirrors:Vector.<Mirror> = new Vector.<Mirror>(); //a vector is an array, but every member has to be (or subclass) the specified class
public var globes:Vector.<Globe> = new Vector.<Globe>();
public var lines:Vector.<Line> = new Vector.<Line>();
trace('lightstage: working');
//create level object
public var curLevel:int = -1;
//create dependent variables
public var kill: Boolean = true;
//init function
public function LightStage() {
//setup MovieClips
var i:int = 0;
for (i = 0; i < 4; i++) {
mirrors.push(new Mirror());
}
for (i = 0; i < 4;i++ ) {
globes.push(new Globe());
}
var tmpLine:Line;
for (i = 0; i < 10; i++) {
tmpLine = new Line();
lines.push(tmpLine);
addChild(tmpLine);
tmpLine.visible = false;
}
//create ENTER_FRAME listener
stage.addEventListener(Event.ENTER_FRAME,enterFrame);
//start the game
levelUp();
}
//levelUp function
public function levelUp() {
curLevel++;
curLine = lines[curLevel]; //set line to the current level
curLine.curX = 0;
curLine.curY = 200;
curLine.draw(550, 200);
curLine.visible = true;
//show and position mirrors and globes
curMirror = mirrors[curLevel];
addChild(curMirror);
curMirror.x = 250;
curMirror.y = 350;
var curGlobe:Globe = globes[curLevel];
addChild(curGlobe);
curGlobe.x = 100;
curGlobe.y = 50;
//set mirror types
curMirror.gotoAndStop(2);
trace("you are now on level " + (curLevel + 1) + "!");
}
//ENTER_FRAME function
public function enterFrame(event:Event) {
//line1.visible = true;
for (var i:int = 0; i < lines.length;i++){
if (i < lines.length - 1) nextLine = lines[i + 1]; //check for out of bounds before assignment next line
if (lines[i].visible == true) {
kill = true;
for each(var mirror:Mirror in mirrors) {
if (lines[i].visible && mirror.stage && mirror.hitTestObject(lines[i])) { //for efficiency, do the hit test last in the if statement
for each(var globe:Globe in globes) {
//Looped through Mirrors and Lines and checked for collision - if collision is present, we loop through globes here
if (nextLine && nextLine.stage) {
addChild(nextLine);
}
//check for active globes
if (lines[i].visible && lines[i].hitTestObject(globe)) {
//check if the selected line touches the selected globe - if it does then we will start the timer for that globe
if (!globe.running){
globe.start();
//trace('timing');
kill = false;
}
}
else {
globe.reset();
}
switch(mirror.currentFrame) {
case 1:
break;
case 2:
//trace('live a life you will remember' + Math.random());
if(nextLine) nextLine.visible = true;
lines[i].draw(mirror.x + (mirror.width / 2),lines[i].curY);
if (nextLine) {
nextLine.curX = mirror.x + (mirror.width / 2);
nextLine.curY = 200;
nextLine.draw(mirror.x + (mirror.width / 2), 0);
}
kill = false;
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
trace(mirror.currentFrame);
kill = false;
break;
}
}
}
else if (lines[i].visible && mirror.stage && lines[i].stage){
if (kill && nextLine){
nextLine.graphics.clear();
nextLine.visible = false;
}
}
}
}
}
}
}
}
//MIRROR CLASS DECLARATION
import flash.events.MouseEvent;
class Mirror extends MovieClip {
trace('mirror: working');
public function Mirror() {
this.addEventListener(MouseEvent.MOUSE_DOWN,onDown,false,0,true);
}
private function onDown(e:MouseEvent):void {
//add the mouse up listener on the stage, that way it's consistent even if the user drags so fast that the mouse leaves the bounds of the mirror
stage.addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
this.startDrag();
}
private function onUp(e:MouseEvent):void {
//we need to remove the listener from the stage now
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp, false);
this.stopDrag();
}
}
//LINE CLASS DECLARATION
import flash.display.Graphics;
class Line extends MovieClip {
trace('line: working');
public var curX:int;
public var curY:int;
public function Line():void {
}
public function draw(toX:int,toY:int):void {
graphics.clear();
graphics.lineStyle(1,0x000000,1);
graphics.moveTo(curX,curY);
graphics.lineTo(toX, toY);
curX = toX;
curY = toY;
}
}
//GLOBE CLASS DECLARATION
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.utils.Timer;
class Globe extends MovieClip {
trace('globe: working');
private var timer:Timer = new Timer(3 * 100, 5);
public function Globe():void {
timer = new Timer(300, 5);
timer.addEventListener(TimerEvent.TIMER, repeatShine, false, 0, true);
}
public function reset():void {
timer.reset();
}
public function start():void {
timer.start();
}
public function get running():Boolean { return timer.running; };
private function repeatShine(e:TimerEvent):void {
}
}

Issue with sharedObject usage / loading data

The main goal of my code is to create a 3x3 grid and when you click a cell from that grid you cant click it again even if you close the fla and load it again.
Something like a shop where the 1st row is level1 of the upgrade and the columns are the other levels.
There are also 2-3 other things that it does -> every cell of the grid has 4 mouseStates.
Also at the 1st load of the FLA you create the 3x3 grid and you can click only on the elements in the 1st row.(you cant get Speed 2 if you didnt have Speed1 before that.)
So you can click the 2nd element of a column only if the 1st element of the same column has been clicked before.
The same goes for the 3rd element of the column -> it can be clicked only if the 2nd was clicked before.
But im having trouble with the logic after loading the fla for the 2nd time.
To be more specific :
It is changing the mouseOver/out states on the elements that were clicked before(which is good (cause i want to see that)), but it is leting me click only the 1st row.And since Im loading the clickedBefore buttons and removing the mouseEvent.CLICK from them, I cant click some of them if i haven`t clicked them at the 1st load of the fla.
I have 2 classes: Main
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.getDefinitionByName;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Graphics;
import flash.display.Bitmap;
import flash.display.SimpleButton;
import flash.net.SharedObject;
public class Main extends Sprite
{
private var elementRow:int = 0;
private var elementCol:int = 0;
private var myClassImage_Arr:Array = new Array();//this contains the different mouseState Images in Class data.
private var myBitmapNames_Arr:Array = ["speed1_", "speed2_", "speed3_",
"time1_", "time2_", "time3_",
"turbo1_", "turbo2_", "turbo3_",];
//------------------------------------------
private var index:int = 0;
private var col:int = 3;
private var row:int = 3;
//------------------------------------------
private var savedData:SharedObject = SharedObject.getLocal("ZZZ_newWAY_nextButton+imageChange_7");
private var buttonThatHaveBeenClicked_Arr:Array = [];
private var myButtons_Arr:Array = [];
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
for (var i:int = 0; i < col; i++)
{
var lastRowElement:BitmapButton = null;
for (var j:int = 0; j < row; j++)
{
for (var k:int = 0; k < 4; k++)//4states of mouse
{
var cls:Class = Class(getDefinitionByName(myBitmapNames_Arr[index] + k));
myClassImage_Arr.push(cls);
}
var myImage_mc = new BitmapButton(myClassImage_Arr[0 + (index * 4)],
myClassImage_Arr[1 + (index * 4)],
myClassImage_Arr[2 + (index * 4)],
myClassImage_Arr[3 + (index * 4)], i, j);
myImage_mc.x = 100 + i * (myImage_mc.width + 10);
myImage_mc.y = 100 + j * (myImage_mc.height + 10);
myImage_mc.name = "myImage_mc" + index;
this.addChild(myImage_mc);
myButtons_Arr.push(myImage_mc)
myImage_mc.mouseEnabled = false;
myImage_mc.mouseChildren = false;
myImage_mc.buttonMode = false;
myImage_mc.addEventListener("send_SOS", onCustomClick);
if ( lastRowElement == null )
{
myImage_mc.mouseEnabled = true;
myImage_mc.mouseChildren = true;
myImage_mc.buttonMode = true;
}
else
{
lastRowElement.next_1 = myImage_mc;
}
lastRowElement = myImage_mc;
index++;
}
}
if(savedData.data.myArray == undefined) trace(" 1st time loading this game\n")
else if(savedData.data.myArray != undefined)
{
trace(" Game was played before\n")
buttonThatHaveBeenClicked_Arr = savedData.data.myArray;
var savedData_length:int = savedData.data.myArray.length;
trace("Buttons that have been clicked before: " + buttonThatHaveBeenClicked_Arr + "\n");
for (var m:int = 0; m < myButtons_Arr.length; m++)
{
var myButtons_ArrName:String = myButtons_Arr[m].name
for (var p:int = 0; p < savedData_length; p++)
{
if(myButtons_ArrName == savedData.data.myArray[p])
{
myButtons_Arr[m].alpha = 0.9
myButtons_Arr[m].buttonMode = false;
myButtons_Arr[m].removeEventListener("send_SOS", onCustomClick);
myButtons_Arr[m].myInsideBtn.upState = myButtons_Arr[m].image3
myButtons_Arr[m].myInsideBtn.overState = myButtons_Arr[m].image4
}
}
}
}
}
private function onCustomClick(ev:Event):void
{
trace(ev.target.name);
if (ev.target is BitmapButton)
{
var btn:BitmapButton = ev.currentTarget as BitmapButton;
if (btn.next_1 != null)
{
btn.next_1.mouseEnabled = true;
btn.next_1.mouseChildren = true;
btn.next_1.buttonMode = true;
}
btn.mouseChildren = false;
btn.buttonMode = false;
btn.removeEventListener("send_SOS", onCustomClick);
buttonThatHaveBeenClicked_Arr.push( btn.name );
savedData.data.myArray = buttonThatHaveBeenClicked_Arr;
savedData.flush();
savedData.close();
}
}
}
}
and BitmapButton
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.Event;
public class BitmapButton extends Sprite
{
public var next_1:BitmapButton = null;
//-----------------------------------
public var myInsideBtn:SimpleButton = new SimpleButton();
private var image1:Bitmap;
private var image2:Bitmap;
public var image3:Bitmap;
public var image4:Bitmap;
public var imageIsInRow:int;
public var imageIsInCol:int;
public function BitmapButton(active_OutState:Class, active_OverState:Class, notActive_OutState:Class, notActive_OverState:Class,col:int,row:int)
{
image1 = new Bitmap (new active_OutState() );
image2 = new Bitmap (new active_OverState() );
image3 = new Bitmap (new notActive_OutState() );
image4 = new Bitmap (new notActive_OverState() );
imageIsInRow = row;
imageIsInCol = col;
myInsideBtn.upState = image1;
myInsideBtn.overState = image2;
myInsideBtn.downState = myInsideBtn.upState;
myInsideBtn.hitTestState = myInsideBtn.overState;
addChild( myInsideBtn );
myInsideBtn.addEventListener(MouseEvent.CLICK, onClick);
}
private function onClick(ev:MouseEvent):void
{
myInsideBtn.upState = image3;
myInsideBtn.overState = image4;
var myNewEvent:Event = new Event("send_SOS");
this.dispatchEvent(myNewEvent);
trace("CLICK from inside the button");
}
}
}
ill also upload it to this link Grid_with_sharedObject with a zip.
and upload also Grod_before_Using_sharedObject if someone decides that he would help but the code is to messed up
If I'm reading your code correctly, I'd honestly say your problem is sequential. For whatever reason, the setting of the active and inactive rows is occurring BEFORE the data is actually being interpreted into the button states. As a result, the computer sees all buttons as off when it decides whether to make other rows clickable, and THEN updates the state of the buttons.
The easiest way to fix this, I think, would be to split the Main() function into a few sub functions, such as updateButtons() for the function that changes whether a row/button is clickable, and loadData() for the function the loads from the SharedObject. In Main(), put the calls to those functions. This will make Main() easier to work with, and you can call a function multiple times if necessary.
To solve your particular issue, you'd need to get the data for the buttons using the SharedObject FIRST (which obviously is working), and THEN update whether the other buttons are clickable.
A "soft-skills" tip for programming: when you run into a problem, grab a piece of paper, a pencil, and read through your code the way your computer would. Be the computer. Write down variables and their values when they change. Mark when functions are called. You'll spot a lot of errors this way.

AS3 loop movieClip based on set timer

I want to set a duration of time by hitting space bar twice. I then want a movieclip to play for that exact amount of time, then loop to play again at for that set amount of time, and so on. until I set a different amount of time by hitting the space bar twice again.
var beat:int;
var beatcount:int;
var tempopress:int;
var num:Number;
num = 0;
tempopress = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN,checker);
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
var myTimer:Timer=new Timer(20,0);
myTimer.addEventListener(TimerEvent.TIMER, stopWatch);
function stopWatch(event:TimerEvent):void {
beatcount = Number(myTimer.currentCount);
}
function checker(e:KeyboardEvent){
if(e.keyCode==Keyboard.SPACE){
if (tempopress == 0) {
trace('start');
beatcount = 0;
myTimer.reset();
myTimer.start();
tempopress = 1;
} else {
trace('stop');
myTimer.stop();
trace(beatcount);
tempopress = 0;
}
}
}
stage.addEventListener(Event.ENTER_FRAME, loopPlayback);
function loopPlayback() {
var loopTimer:Timer=new Timer(20,beatcount);
myTimer.addEventListener(TimerEvent.TIMER, loopWatch);
}
function loopWatch(event:TimerEvent):void {
if (MovieClipMan.currentFrame >= MovieClipMan.totalFrames ){
MovieClipMan.gotoAndStop(1);
} else {
MovieClipMan.nextFrame();
}
}
I know it's a mess haha. Please help! :]
I'd perhaps try something like this, which essentially is checking to see whether to do the loop or not each frame.
var timeStart:Number;
var loopDuration:Number;
var timeLastLoop:Number;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onKeyDown(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.SPACE) {
if (!timeStart) { // First time SPACE is hit
timeStart = getTimer();
} else { // Second time SPACE is hit
loopDuration = getTimer() - timeStart; // set the loop duration
timeStart = NaN; // reset the start time
loop();
}
}
}
function onEnterFrame(e:Event):void {
if (loopDuration && timeLastLoop) {
if (getTimer() >= timeLastLoop + loopDuration) { // if it's time to loop
loop();
}
}
}
function loop():void {
timeLastLoop = getTimer();
someMovieClip_mc.gotoAndPlay(0);
}
First, use getTimer() to find the difference in time between space bar keypress.
Next, would be to stop creating a new Timer in every frame. It should be created outside of the enter frame handler. Then on the second keypress, you can set the delay property to the difference, and restart the timer.
The most important changes would be here:
if (tempopress == 0) {
trace('start');
myTimer.stop();
startTime = getTimer();
beatcount = 0;
tempopress = 1;
} else {
trace('stop');
myTimer.delay = getTimer() - startTime;
myTimer.reset();
myTimer.start();
tempopress = 0;
}
Then, the timer event handler can just send the MovieClip to frame 1.

Set timer with random interval

I have the current code:
enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
How do I change the timer so that instead of triggering sendEnemy every 2 seconds, it triggers it at a random time between 1 and 3 seconds?
The Timer class possess the delay property which indicates the delay between two "timer" events. So, you just have to randomly change the delay (for the next spawn) at the beginning of 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.
}
Triggering between 1 and 3 seconds, means that each second it has 33% chance to be triggered. So:
enemyShipTimer = new Timer( 1000 );
enemyShipTimer.addEventListener("timer", function( e:TimerEvent ):void
{
if( Math.random() < 0.33 )
{
trace( "triggered!" );
}
});
enemyShipTimer.start();
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();
}
}
}
You can use the Math.random function.
You can choose the maximum value of the random function by multiplying it.
But your random would still go to zero, so you have to add it with a starting number.
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();