Problems with adding and subtracting time from/to Timers - actionscript-3

Now I am also using a timer in frame 8, which is my Gamescreen frame to try and create an energy bar, so decreasing by 1 every second, and everytime the character collides with an object then increment the value of count by 1 (which in my min is 1sec, right?), however the timer runs out prematurely, when the label is showing 3secs left after collecting 3 items the timer automatically ends, HELP ME! :)
var count:Number = 5; (temporary value for testing)
var theTimer:Timer = new Timer(1000, count);
theTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
theTimer.start();
function whenTimerComplete(e:TimerEvent):void
{
theTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, whenTimerComplete); //Remove listener
gotoAndStop("frameFive"); // Advance to score screen.
}
theTimer.addEventListener(TimerEvent.TIMER, theCountdown);
function theCountdown(e:TimerEvent):void
{
count--;
timerLabel.text = count.toString()
}
//Start the timer and show in the label.
timerLabel.text=count.toString();
theTimer.start();
All help and a solution is VERY much appreciated.

Here's an example countdown timer:
Launch Flash example
FLA source code
Countdown Timer AS3 source code
CS6 ZIP of source code
CS5 ZIP of source code
Create a countdown timer class at the root of your FLA:
CountdownTimer.as
package {
import flash.events.TimerEvent;
import flash.utils.Timer;
public class CountdownTimer extends Timer {
public var time:Number = 0;
public function CountdownTimer(time:Number = Number.NEGATIVE_INFINITY, delay:Number = 1000) {
super(delay, repeatCount);
if (!isNaN(time))
this.time = time;
repeatCount = Math.ceil(time / delay);
addEventListener(TimerEvent.TIMER, timerHandler);
}
protected function timerHandler(event:TimerEvent):void {
time -= delay;
if (time == 0)
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
}
public function dispose():void {
removeEventListener(TimerEvent.TIMER, timerHandler);
}
}
}
On the timeline of your FLA, create a timer with the total number of milliseconds to countdown:
var timer:CountdownTimer = new CountdownTimer(60000);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
timer.start();
In the example above, the timer will countdown for 1-minute (60-seconds). Each second the timerHandler will be called. When it reaches 0, the timerCompleteHandler will be called.
function timerHandler(event:TimerEvent):void {
timerText.text = (timer.time / 1000).toString();
}
function timerCompleteHandler(event:TimerEvent):void {
timerText.text = "COMPLETE";
}
To add time to the timer, add milliseconds to time. If you want the timer to dispatch timer complete event when it reaches 0, update the repeatCount:
timer.time += 1000;
timer.repeatCount += 1;
Likewise to remove time from the timer, subtract milliseconds from time; and again, if you want the timer to dispatch timer complete event when it reaches 0, update the repeatCount:
timer.time -= 1000;
timer.repeatCount -= 1;

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

ActionScript 3.0 End Game Countdown Timer

I'm making a game in actionscript 3.0. I currently have a countdown timer (counts down from 30 seconds). Once the 30 seconds is up I want the frame to move from frame 2 to frame 3. I have put gotoAndStop(3) in the code under the timer but when the timer starts it goes to frame 3 straight away. It doesnt go to frame 3 when the 30 seconds is up. I would appreciate any help at all!
var nCount:Number = 30;
var myTimer:Timer = new Timer(1000, nCount);
timer_text.text = nCount.toString(nCount);
myTimer.start();
myTimer.addEventListener(TimerEvent.TIMER, countdown);
function countdown(e:TimerEvent):void
{
nCount--;
timer_text.text = nCount.toString();
gotoAndStop(3);
}
You are calling gotoAndStop(3); on the very first timer event, i.e. after one second since you are not checking the value of nCount. You need to call gotoAndStop(3); only when nCount is zero.
function countdown(e:TimerEvent):void {
nCount--;
timer_text.text = nCount.toString();
if (nCount == 0) {
gotoAndStop(3);
}
}

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 can we reset the repeatCount property while the timer is running

How can we reset the repeatCount property while the timer is running.
In a game a countdown timer starts running at 120. If the user clicks on "hint" button i need to reduce the time by 5 seconds and start displaying the countdown
Now the problem is the countdown timer is reduced by five but the Timer runs till "-n*5".
"n" being the number of times hint button clicked.
How to solve this issue?
Here's one approach to your problem. Maintain a timer count separate from the Timer's repeatCount, and stop when that separate counter hits 0, instead of when the TimerComplete event occurs.
public var t:Timer;
public var count:int = 120;
protected function init(event:FlexEvent):void
{
t = new Timer(1000,count);
t.addEventListener(TimerEvent.TIMER, onTimer);
t.start();
}
protected function onTimer(evt:TimerEvent):void
{
count--;
//display count as time remaining
if (count <= 0)
{
//out of time!
t.stop();
}
}
protected function onHint(evt:MouseEvent):void
{
count-=5;
//update time or wait for next tick
}