Countdown timer in a flash game - actionscript-3

I'm making a simple helicopter game to try and get into making flash games. I wanted to make a countdown timer that will count down from 3 seconds, then start the loop, but I'm not sure how to go about is. I don't use the frames in flash, rather I use action script (3) to make an "ENTER_FRAME" loop, if that helps. It looks like this:
addEventListener(Event.ENTER_FRAME, mainLoop);
I'm sure I need to put the timer above it, I'm just not sure how to make a timer. Any advice will probably help, as I'm new to AS3, thanks.

To make a countdown timer, you can use a Timer, like this :
trace('3');
// create a timer with : delay: 1 second, repeats: 3
var timer:Timer = new Timer(1000, 3);
timer.addEventListener(
TimerEvent.TIMER,
// on every repeat
function(e:TimerEvent):void {
trace(Math.abs(timer.currentCount - 3)); // gives : 2, 1, 0
}
)
timer.addEventListener(
TimerEvent.TIMER_COMPLETE,
// at the timer end
function(e:TimerEvent):void {
// do other instructions
trace('go');
}
)
// start the timer
timer.start();
Hope that can help.

I hope i can help you with your code. What im getting is that you try to make 3 seconds count down then start somewhere.
yes you need a timer :
var theTime:Timer
theTime = new Timer(countDownLoading*1000); //1000 is in milisecond
var countDown = 1;
var totalCountDown = 3; // How long it'g gonna count
var countDownLap = totalLoading;
theTime.addEventListener(TimerEvent.TIMER,tick); //adding timer event
function tick(e:TimerEvent){
if(countDownLap == 0)//if the cound down is 0
{
time.stop();
gotoAndStop(2);
trace("Finish counting");
} else { //not counting down yet, then lets count
countDownLap = countDownLap - countDown; //
trace(countDownLap);
}
//timer goes like the ticking clock so if the count down is not 0.
//everytime the ticking starts the cound down (3) - 1
}
I hope this help.

Related

Actionscript 3 Control Timeline after Duration of no input from user

can anyone help me with this. I know its something very basic, but I just cant work it out.
What I need is for the timeline gotoandstop at frame 1 after 15 seconds of inactivity.
Basically this is for a directory board so if no one is using it, it will return back to the home screen after a period of inactivity.
Any help would be greatly appreciated.
Thankyou
What you can do, is use a Timer object. Then, whenever the user moves the mouse or clicks or presses a key, reset that timer back to 15 seconds.
On your frame 1, make a timer object:
//create the timer object var
var resetTimer:Timer;
//if it doesn't exist yet, create a new timer object and assign it to that var
if(!resetTimer){
resetTimer = new Timer(15000,1); //tick 1 time with a delay of 15
//listen for the TIMER event (fires when the delay is up)
resetTimer.addEventListener(TimerEvent.TIMER, reset);seconds
}else{
resetTimer.reset(); //if it did previously exist, stop/reset it (for when you revisit frame 1)
}
//go back to the first frame if the timer fires
function reset(e:Event = null):void {
resetTimer.reset(); //reset the timer
gotoAndStop(1); //go to frame 1
}
//LISTEN for various user input type events on stage (globally)
stage.addEventListener(MouseEvent.MOUSE_DOWN, userInput);
stage.addEventListener(MouseEvent.MOUSE_MOVE, userInput);
stage.addEventListener(KeyboardEvent.KEY_DOWN, userInput);
stage.addEventListener(KeyboardEvent.KEY_UP, userInput);
//if there was user input, reset the timer and start it again
function userInput(e:Event = null):void {
resetTimer.reset();
resetTimer.start();
}
The only thing left to do is, when you leave frame 1 and want the timeout to be applicable call resetTimer.start(). Presumably that would be on frame 2.
its possible to simulate it so:
class test extends MovieClip{
public var myTimer:Number;
public var input:TextField;
function test(){
myTimer=0;
input=new TextField();
this.addChild(input);
this.addEventListener(Event.ENTER_FRAME,timer);
input.addEventListener(Event.CHANGE, input_from_user);
}
function timer(ev){
myTimer +=(1/25);//if the frame rate is 25 frame per sconde
if(myTimer ==15){
this.gotoAndStop(1);
this.removeEventListener(Event.ENTER_FRAME,timer);
}
}
function input_from_user(ev){
myTimer =0;
}
}

How to Increase a timer AS3

Hey everyone cant really figure out the easiest approach to this problem.
Basically I have a timer that starts in the beginning of the game like so:
//Create new timer object
tEggTimer = new Timer (nTimerSpeed);
//Listen for timer intervals
tEggTimer.addEventListener(TimerEvent.TIMER, addEggs, false, 0, true);
//start timer
tEggTimer.start();
The nTimerSpeed is equal to (800);
Then I add the eggs like so:
private function addEggs(e:TimerEvent):void
{
//var eggGlobalPosition:Point = _Egg.localToGlobal(new Point(_Bunny.x, _Bunny.y));
_Egg = new mcEgg();
stage.addChild(_Egg);
_Egg.x = _Bunny.x;
_Egg.y = _Bunny.y + 30;
aEggArray.push(_Egg);
trace(aEggArray.length);
}
So in another enter frame function I want to change the value of the timer to (500), but whenever I try like so:
tEggTimer = new Timer (500);
tEggTimer.start();
like So:
private function updateDifficulty():void
{
if (difficultyUpdate) return;
if (nScore >= 2)
{
tEggTimer.removeEventListener(TimerEvent.TIMER, addEggs);
tEggTimer.stop();
tEggTimer = new Timer(200);
tEggTimer.addEventListener(TimerEvent.TIMER, addEggs);
tEggTimer.start();
But this doesnt do anything but stop the timer entirely.
What can I do in order to decrease the timer correctly?
Thanks guys.
If you just want to change the timer speed, while keeping everything else the same, you could just change the delay property in the timer object.
Sample here:
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
var speeds:Vector.<int> = new <int>[1000, 2000, 5000];
var currentSpeed:int = 0;
var timer:Timer = new Timer(speeds[currentSpeed]);
function timerTick(inputEvent:TimerEvent):void {
trace("Timer ticking: "+ getTimer());
}
timer.addEventListener(TimerEvent.TIMER, timerTick, false, 0, true);
timer.start();
function clickedStage(inputEvent:MouseEvent):void {
currentSpeed = ++currentSpeed % speeds.length;
timer.delay = speeds[currentSpeed];
trace("Timer delay set to "+ timer.delay);
}
this.stage.addEventListener(MouseEvent.CLICK, clickedStage, false, 0, true);
Clicking on the stage will change the timer delay from 1 second, 2 seconds, 5 seconds and cycle. I'm just using getTimer() to show the rate of which the timer is ticking.
Note that it seems from the output, every time the value is changed, the timer will automatically restart.
timer.reset();
timer.delay = 2000;
timer.start();
May no be the best way but, instead using nTimerSpeed, make it run through every millisecond:
tEggTimer = new Timer (1);
Then in your AddEggs function use nTimerSpeed and a counter variable. counter is initialize to 0. Incase all your logic in an if statement, increment counter every time through function. if counter equals nTimerSpeed, allow for them inside the if statement and reset counter.
function AddEggs()
{
if(counter == nTimerSpeed)
{
//adding eggs logic
counter = 0;
}
counter++;
}
Did you try saying: tEggTimer.stop() just before re-instantiating with the 500 ms version? I'm guessing that your first Timer instance will just keep firing as your new one starts, unless you deliberately stop it.

AS3 Think time simulation

In my cards game, I'm trying to simulate the opponent to think about his choice. During this time I want to let appear on the screen a thinking cloud... this is possible with the command TCloud.visible = true; and false to let it disappear. After the think time (5 seconds) I want some more seconds ( like 2-3 seconds) so you can see what the opponent has decided, and then start again... I've already written the logic part of the actions, just need you to help me with this problem.
You have to use the Timer class and do something like this:
// create a timer that dispatch an event after 3 seconds
private function wait3seconds():void {
var timer:Timer = new Timer(3000, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
timer.start();
}
private function onTimerComplete(event:TimerEvent):void {
// do something
}

looping a function in action script

hi guys I've been trying this for hours, buts still i can't loop this function, at least i want to repeat it unto 5 times, but it only loop for once, i tried using for loop, while, and do while, but still it won't loop
var myTimer:Timer = new Timer(1000); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runMany);
myTimer.start();
function runMany(event:TimerEvent):void {
myTimer.stop();
myTimer.start();
trace("runMany() called # " + getTimer() + " ms");
if(getTimer() > 3000)
{
//random call of captopn and costumer in 3 seconds
myTimer.stop();
capsChoice = randomRange(1, 3);//random caption
costumChoice = randomRange(1, 3);//randomcostum
//condition in caption
more codes in here………...
}
}
Try removing myTimer.stop() in the eventlistener function, because that function call stops your entire Timer object once it's called.
Also, when you create a Timer, you can give it a repeat counter in the Constructor Paramters.
var myTimer:Timer = new Timer(1000, 5); // 1 second, repeat 5 times
myTimer.addEventListener(TimerEvent.TIMER, runMany);
myTimer.start();
function runMany(event:TimerEvent):void {
//...
this will call the function 5 times with a delay of 1 second between executions.
And another thing to keep in mind, you only need to start the timer once, if you call myTimer.start() in the listener function every time, it will try to loops of 5 executions again and again, leading to an infinite loop.
See also : AS3 Documentation Timer
Working with the Timer Class

How to only execute something every 30 frames

My question is this, I want to add a rock every second (30 frames per second), I have different levels, this means I have different amounts of rocks in each level and I have different amount of speeds, so I want to add 10 rocks in a total of 30 seconds in level 1
in level 2 it's 20 rocks in a total of 20 seconds etc. I'm open to completly changing it, I just want the best solution. I want it to be dynamic so I can make a lot of levels. How should I got about doing this
I don't want to keep a counter and every time it's at 30 then add a rock and reset it.
Thank you in advance
switch(difficulty)
{
case 1:
timer = 30;
numberOfRocks = 10;
break;
case 2:
timer = 20;
numberOfRocks = 20;
break;
case 3:
timer = 10;
numberOfRocks = 30;
break;
case 4:
timer = 5;
numberOfRocks = 40;
break;
}
addEventListener(Event.ENTER_FRAME, loop)
}
private function loop(e:Event):void
{
for (var i:int = 0; i < (timer * 30); i++)
{
a_bitmap = new a_class();
a_bitmap.x = 750;
a_bitmap.y = Math.ceil(Math.random() * (600 - a_bitmap.height));
a_bitmap.height = 35;
a_bitmap.width = 35;
addChild(a_bitmap);
a_bitmap.name = "astroid" + i + "";
myArray.push(true);
}
}
A Timer may work better for you're needs than a frame handler. I'd recommend using math to calculate your level parameters instead of hard-coded switch statements, then you can add as many levels as you'd like (or have your game go indefinitely)
var rockLoadTimer:Timer;
function gameInit():void {
//your games initialization code here
//create a timer that fires every second when running
rockLoadTimer = new Timer(1000);
//the function to call every time the timer fires. You could also listen for TIMER_COMPLETE is wanted to run a function once all rocks are loaded
rockLoadTimer.addEventListener(TimerEvent.TIMER, addNextRock);
}
function startLevel(difficulty:int = 1):void {
//your code here to clear the level
//repeat count is used as the amount of rocks to load this level - level number times 10
rockLoadTimer.repeatCount = difficulty * 10;
//the delay time is how quickly you want the rocks to load. this is 5 seconds divided by the difficulty level
//so the first level would be every 5 seconds, second would be every 2 and a half seconds, third level would be every second and two thirds. etc.
rockLoadTimer.delay = Math.round(5000 / difficulty);
rockLoadTimer.reset();
rockLoadTimer.start();
}
function addNextRock(e:Event = null):void {
//your rock creation code here
}
You can use a Timer, and create an instance of a_class during each tick:
var timer:Timer = new Timer(1000, 30); // One per second for 30 seconds
timer.addEventListener(TimerEvent.TIMER, addAsteroid);
timer.start();
function addAsteroid():void {
a_bitmap = new a_class();
// etc.
}
The timer delay is "asteroids per millisecond", so if you want to create 10 over 30 seconds you would set it to 30000/10 = 3000.
However, this approach works best when there is a smooth framerate- it will execute once per second, but the number of frames of animation can vary if Flash is running at less than 30fps. If your game works how I think it does, this could result in asteroids being "bunched up". So, keeping a counter might be the better solution here, unless you plan on handling the rest of your game logic (i.e. asteroid movement speed) in a way that can account for variations in frame rate.
If you want to use a counter:
var creationCounter:Number = 0; // put this at class level
// Then in the ENTER_FRAME event:
creationCounter += asteroids_per_second / 30;
while (creationCounter-- >= 1) {
a_bitmap = new a_class();
// etc.
}
You can also use flash.utils.setInterval function .
setInterval(trace , 1000 , "trace message once per second");
If you use TweenLite, you can use the delayedCall function, it can use time or frames,
// delayedCall(delay:Number, onComplete:Function, onCompleteParams:Array = null, useFrames:Boolean = false):TweenMax
TweenLite.delayedCall(30, addAstroid, null, true);
More info, see the docs: http://www.greensock.com/as/docs/tween/com/greensock/TweenMax.html#delayedCall()