AS3 on frame load reduce Countdown time - actionscript-3

I have the following countdown that will send the player to another frame if countdown equals 0.
I need to update the code to reduce this countdown in 0,05 secs every time the frame is loaded.
Ex of what i want in frame 2 actions:
1st time: var CountDown:Number = 3;
2nd time: var CountDown:Number = 2,95;
3rd time: var CountDown:Number = 2,90;
4th ...
can you please help me??
Tks a lot!!
Code:
import flash.events.MouseEvent;
stop();
var fl_SecondsToCountDown_2:Number = 3;
var fl_CountDownTimerInstance_2:Timer = new Timer(1000, fl_SecondsToCountDown_2);
fl_CountDownTimerInstance_2.addEventListener(TimerEvent.TIMER, fl_CountDownTimerHandler_2);
fl_CountDownTimerInstance_2.start();
function fl_CountDownTimerHandler_2(event:TimerEvent):void
{
//trace(SecondsToCountDown_2 + " seconds");
fl_SecondsToCountDown_2--;
if(fl_SecondsToCountDown_2 == 0){
gotoAndStop ("lost");
}
}

I'm not sure if I understood what you want but you can try this :
1st frame :
I created a button just to go to the 2nd frame ( I didnt know how you go to your 2nd frame ) :
import flash.events.MouseEvent
btn.addEventListener(MouseEvent.CLICK, btn_on_Press)
function btn_on_Press(e:MouseEvent){
gotoAndPlay(2)
}
stop()
2nd frame :
// if count_down didnt exist, we create it
if(!count_down) var count_down:Number = 3
else count_down -= 0.05
// sometimes the operation give us result like this : 2.9000000000000004 so we should fixe decimals
trace(count_down.toFixed(2))
// go tp your "lost" frame
if(count_down <= 0) gotoAndStop('lost')
// return to 1st frame
else gotoAndStop(1)

Related

Error 1009-handling

I want to make counterdown in quiz. In my quiz, after endtime it will go to another frame. The time is about 10 minutes, exactly. In this code I just write in 31 second to make it simple.
This is my code
import flash.events.*;
import flash.utils.Timer;
import flash.utils.getTimer;
stop()
var totSec:int = 31;
var totTime:Number = 1000 * totSec;
var secTimer:Timer = new Timer(1000,totSec);
secTimer.start ();
secTimer.addEventListener (TimerEvent.TIMER, updateClock);
function updateClock (t:TimerEvent) {
var timePassed:int = totTime - getTimer();
var second:int = Math.floor(timePassed/1000);
var minute:int = Math.floor(second/60);
//trace ("second : " + second);
second %= 60;
var sec:String = "";
sec = String(second);
if (second < 10)
{
sec = "0" + second;
}
var showTime:String = minute + " : " + sec;
timeDisplay.text = String(showTime)
if (minute == 0 && second == 0 )
{
gotoAndPlay(525);
//addEventListener (Event.ENTER_FRAME, stopTime);
trace ("Times up");
secTimer.start ();
}
}
But, when the frame go to frame 525, I get this error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at adminserver/updateClock()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
The issue:
Your timer actually ticks one more time after you do the following:
gotoAndPlay(525);
//addEventListener (Event.ENTER_FRAME, stopTime);
trace ("Times up");
secTimer.start(); <---------not sure what this is about?
So when it ticks again, you've actually gone to a different frame (525) where your timeDisplay text field no longer exists (presumably) - so the code errors.
when you change frames, code attached to listeners keeps running even if that code wasn't on the current frame
The Cleanest Solution
Instead of doing your own math to figure out when the timer is done, use the actual timer event for such:
secTimer.addEventListener(TimerEvent.TIMER_COMPLETE, .....
This way, you know the timer is done before your code runs and you change frames.
Here is a full example, along with some tips:
stop();
var totSec:int = 31;
//no need for this var, total time in your case is secTimer.repeatCount * secTimer.delay
//var totTime:Number = 1000 * totSec;
var secTimer:Timer = new Timer(1000,totSec);
secTimer.addEventListener(TimerEvent.TIMER, updateClock);
//listen for the complete event when the timer is all done
secTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerComplete);
secTimer.start();
function updateClock (e:TimerEvent) {
//the timer's currentCount will be how many times the timer has ticked,
//which in this case will be seconds elapsed.
//If you subtract that from the total repeat count, you'll get the seconds left,
//no need to use getTimer, which is now allows you to pause your timer if you'd like (can't pause using getTimer)
var second:int = secTimer.repeatCount - secTimer.currentCount;
var minute:int = Math.floor(second/60);
//trace ("second : " + second);
second %= 60;
var sec:String = String(second);
if (second < 10){
sec = "0" + second;
}
var showTime:String = minute + " : " + sec;
timeDisplay.text = String(showTime);
}
function timerComplete(e:TimerEvent):void {
trace ("Times up");
//secTimer.start(); //you don't really want to start the timer again - which does nothing anyway without a secTimer.reset() first
//you should also remove the listeners on the timer so it can freed for garbage collection
secTimer.removeEventListener(TimerEvent.TIMER, updateClock);
secTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, timerComplete);
gotoAndPlay(525);
}
I think that to avoid that error, you should stop that Timer before going to another frame :
// ...
trace ("Times up");
secTimer.stop();
gotoAndPlay(525);
// ...
Hope that can help.

Countdown timer in a flash game

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.

Adding additional time to main timer from movieclip?

Hi so yeah in the main timeline I have the timer
var count:Number = 300;//Count down from 300
var myTimer:Timer = new Timer(1000,count);
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
function sayHello(e:TimerEvent):void
{
trace("Current Count: " + myTimer.currentCount);
}
And when you go into the movieclip reimoi_mcand click the useplush button I want to be able to add additional seconds onto the timer. The following is the code in the reimoi_mc clip but yeah I really have no idea how to make this work, please help ;0; (I have to use MovieClip(root) to access the running timer from the main timeline within the movieclip)
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
stop();
useplush.addEventListener(MouseEvent.CLICK, addtime);
function addtime(e:MouseEvent):void
{
MovieClip(root).count += 2;
MovieClip(root).myTimer.repeatCount += MovieClip(root).count; //add time to the timer
trace("new time " + myTimer.currentCount);
}
I think what you are trying to do is add 2 seconds to the timer in the click handler, and then show how much time is left? If so, just a couple tweaks will do:
function sayHello(e:TimerEvent):void {
trace("Time Left: " + myTimer.repeatCount - myTimer.currentCount); //time left is the repeat count - the current count
}
function addtime(e:MouseEvent):void {
MovieClip(root).myTimer.repeatCount += 2 //add 2 more ticks to the timer (currentCount will always remain the same unless the timer is reset)
trace("new time remaining: " + MovieClip(root).myTimer.repeatCount - MovieClip(root).myTimer.currentCount);
}
BONUS CODE!
If you wanted to make it agnostic of the timer delay (let's say you want it to update quicker than 1 second for instance), you could do this:
var startingTime:Number = 20; //the initial time in seconds
var myTimer:Timer = new Timer(200); //your timer and how often to have it tick (let's say 5 times a second)
myTimer.repeatCount = startingTime * Math.ceil(1000 / myTimer.delay); //set the initial repeat count
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
myTimer.start();
function sayHello(e:Event):void {
trace("Time Left: " + ((((myTimer.repeatCount - myTimer.currentCount) * myTimer.delay) / 1000)) + "seconds");
}
And in your other object:
stage.addEventListener(MouseEvent.CLICK, function(e:Event){
myTimer.repeatCount += Math.ceil(2000 / myTimer.delay); //add 2000 milliseconds to the timer
});
You'd better use an external counter to count the time, instead of stuffing it into a Timer object. You would then need timers to measure delays, and listeners to count them.
var myTimer:Timer=new Timer(1000); // no second parameter
public var secondsLeft:int=300; // former "count"
myTimer.addEventListener(TimerEvent.TIMER, sayHello);
function sayHello(e:TimerEvent):void {
secondsLeft--;
trace("Seconds left:", secondsLeft);
if (secondsLeft<=0) {
myTimer.stop();
myTimer.reset();
// whatever else to trigger when time runs out
}
}
And then you just add to secondsLeft and update the scoreboard.

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.

How do you stop setInterval() after certain number of iterations

I have tried following code and its working but how do i stop when its reach 130 ?
var textValue:Number = 67.1;
var addValue:Number = .1;
my_txt.text = textValue.toString();
function counter(){
textValue += addValue;
my_txt.text = textValue.toString();
}
setInterval(counter, 10);
setInterval returns a unique ID as an unsigned int (uint). You can use clearInterval with this ID to stop the interval. The code:
var textValue:Number = 67.1;
var addValue:Number = .1;
var myInterval:uint;
function counter(){
textValue += addValue;
my_txt.text = textValue.toString();
if( textValue >= 130 ) {
clearInterval(myInterval);
}
}
myInterval = setInterval( counter, 10 );
You can stop an interval by using clearInterval. Try this:
var textValue:Number = 67.1;
var addValue:Number = .1;
my_txt.text = textValue.toString();
function counter(){
textValue += addValue;
my_txt.text = textValue.toString();
//check for end value
if (textValue>=130)
{
//clear the interval
clearInterval(intervalID);
}
}
//store the interval id for later
var intervalID:uint = setInterval(counter, 10);
Since it seems like you may be using actionscript 3, I suggest not using an interval at all. A Timer object may be better as it can offer better control, such being able to set the number of times it fires off before stopping itself and being able to easily start, stop, and restart the timer as needed.
Example of using a Timer object and adding an event listener for each tick
import flash.utils.Timer;
import flash.events.TimerEvent;
// each tick delay is set to 1000ms and it'll repeat 12 times
var timer:Timer = new Timer(1000, 12);
function timerTick(inputEvent:TimerEvent):void {
trace("timer ticked");
// some timer properties that can be accessed (at any time)
trace(timer.delay); // the tick delay, editable during a tick
trace(timer.repeatCount); // repeat count, editable during a tick
trace(timer.currentCount); // current timer tick count;
trace(timer.running); // a boolean to show if it is running or not
}
timer.addEventListener(TimerEvent.TIMER, timerTick, false, 0, true);
Controlling the timer:
timer.start(); // start the timer
timer.stop(); // stop the timer
timer.reset(); // resets the timer
Two events it throws:
TimerEvent.TIMER // occurs when one 'tick' of the timer has gone (1000 ms in the example)
TimerEvent.TIMER_COMPLETE // occurs when all ticks of the timer have gone (when each tick has happened 11 times in the example)
API Documentation: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html