Timer in as3 initial value - actionscript-3

I have a timer counting up in as3. I am trying to simulate a clock counting up from 07:30 to 12:00. The functionality of the counting is working. How would i set an initial start value and a stop value?
Here is my code:
var timer:Timer = new Timer(100, 50);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 10;
function timerTickHandler(Event:TimerEvent):void
{
timerCount += 10000;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timer_txt.text = minutes + ":" + seconds;
}

There are a few ways you can do this. I'll share 2 of them.
Initialize a date object to your starting time: (before your timer starts ticking)
var time:Date = new Date();
time.setHours(7, 30);
Then append your milliseconds to the time every timer interval:
time.time += milliseconds;
This would be a good way to go if you needed to stop the clock for some reason.
If you don't need to stop the clock ever (and wanted an accurate clock), you could do the following:
var time:Date = new Date();
time.setHours(7,30);
var offset:Number = flash.utils.getTimer(); //this gets the amount of milliseconds elapsed since the application started;
Then in your interval method:
time.time += flash.utils.getTimer() - offset;

Related

Phaser time event won't loop

I am trying to make a timer for my game but whatever I try to make it loop doesn't work and it will only go through once when the scene starts. This isn't my first scene in the game because I need it to start counting only during play.
create: function(){
const self = this
self.startTime = new Date();
self.totalTime = 120;
self.timeElapsed = 0;
self.createTimer();
self.gameTimer = this.time.addEvent({
delay: 100,
callback: self.updateTimer(),
callbackScope: self,
loop: true
});
}
createTimer: function(){
var me = this;
me.timeLabel = me.add.text(600, 40, "00:00", {font: "40px Arial", fill: "#000000"});
me.timeLabel.align = 'center';
},
updateTimer: function(){
console.log("please")
var me = this;
var currentTime = new Date();
//console.log(currentTime)
var timeDifference = me.startTime.getTime() - currentTime.getTime();
console.log(timeDifference)
//Time elapsed in seconds
me.timeElapsed = Math.abs(timeDifference / 1000);
console.log(me.timeElapsed)
//Time remaining in seconds
//Convert seconds into minutes and seconds
var minutes = Math.floor(me.timeElapsed / 60);
var seconds = Math.floor(me.timeElapsed) - (60 * minutes);
//Display minutes, add a 0 to the start if less than 10
var result = (minutes < 10) ? "0" + minutes : minutes;
console.log(result)
//Display seconds, add a 0 to the start if less than 10
result += (seconds < 10) ? ":0" + seconds : ":" + seconds;
me.timeLabel.text = result;
}
I have tried using different methods but it either never repeats or it doesn't work.
The problem is, that you are calling the function self.updateTimer and not "passing" it to the TimerEvent, just change callback: self.updateTimer() to callback: self.updateTimer (remove the brackets) and it will work.
Here the TimerEvent creation:
...
self.gameTimer = this.time.addEvent({
delay: 100,
// you need to pass the function
callback: self.updateTimer,
callbackScope: self,
loop: true
});
...

How to have Timer Count Down AS3

I have a Timer that I am trying to get to countdown instead of up. I worked with this code years ago and can't seem to figure out how to make it count down from 5 minutes.
I've only tried messing with the variables.
Here are my variables etc:
tCountTimer = new Timer(100);
tCountTimer.addEventListener(TimerEvent.TIMER, timerTickHandler);
timerCount = 0;
tCountTimer.start();
Here are my Functions to Count:
private function timerTickHandler(e:Event):void
{
timerCount += 100;
toTimeCode(timerCount);
}
private function toTimeCode(milliseconds:int):void
{
this.milliseconds = milliseconds;
//create a date object using the elapsed milliseconds
time = new Date(milliseconds);
//define minutes/seconds/mseconds
minutes = String(time.minutes + 5);
seconds = String(time.seconds);
miliseconds = String(Math.round(time.milliseconds) / 100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+ minutes : minutes;
seconds = (seconds.length != 2) ? '0' + seconds : seconds;
//display elapsed time on in a textfield on stage
playScreen.timeLimitTextField.text = minutes + ":" + seconds;
}
It counts up perfect but just can't get it to time down from 5 minutes. All help is much appreciate.
Didn't test that, but I hope the idea is absolutely clear.
// Remember the time (in milliseconds) in 5 minutes from now.
var endTime:int = getTimer() + 5 * 60 * 1000;
// Call update function each frame.
addEventListener(Event.ENTER_FRAME, onFrame);
function onFrame(e:Event):void
{
// How many milliseconds left to target time.
var aTime:int = endTime - getTimer();
// Fix if we are past target time.
if (aTime < 0) aTime = 0;
// Convert remaining time from milliseconds to seconds.
aTime /= 1000;
// Convert the result into text:
// aTime % 60 = seconds (with minutes stripped off)
// aTime / 60 = full minutes left
var aText:String = ze(aTime / 60) + ":" + ze(aTime % 60);
// Do whatever you want with it.
trace(aText);
}
// Function to convert int to String
// and add a leading zero if necessary.
function ze(value:int):String
{
return ((value < 10)? "0": "") + value.toString();
}

Stop clock on pause button

I have a "clock" counting down the time of the game (from 9 seconds to 0 seconds). I have a button that pauses the game, so I want to freeze de clock and when I click to play, the game continuos from that second that I frozen. But I don't have any idea how to do this! Can you help me please?
this.addEventListener(Event.ENTER_FRAME, updateTimer);
function updateTimer(e:Event){
var t:uint = getTimer();
var dt:uint = 9000 - t;
var totseconds:uint = Math.floor(dt/1000);
var minutes:uint = Math.floor(totseconds/60);
var seconds:uint = Math.floor(totseconds%60);
var minsWithZ = minutes < 10 ? "0" + minutes : minutes;
var secsWithZ = seconds < 10 ? "0" + seconds : seconds;
var time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
function menuPause(e:MouseEvent){
...somegame code...
voltar.addEventListener(MouseEvent.MOUSE_UP, play);
}
function play (e:MouseEvent){
...some game code
}
You have two choices at least:
1-Andre's answer;
2-my answer:
import flash.events.Event;
var dt:int = 9000
var diff:Number=0;
var prevDiff:Number=0;
var currentTime:Number=0;
var t:uint=0;
var totseconds:int=0;
var minutes:int=0;
var seconds:int=0;
var minsWithZ;
var secsWithZ;
var running:Boolean=true;
var time;
this.addEventListener(Event.ENTER_FRAME, updateTimer);
function updateTimer(e:Event){
if(dt<1){dt=1;menuPause(null)}
trace(running);
totseconds= Math.floor(dt/1000);
minutes= Math.floor(totseconds/60);
seconds= Math.floor(totseconds%60);
minsWithZ = minutes < 10 ? "0" + minutes : minutes;
secsWithZ = seconds < 10 ? "0" + seconds : seconds;
time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
if(running){
t= getTimer()-diff-prevDiff;
dt=5000- t;
}else{
diff=getTimer()-currentTime;
}
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
voltar.addEventListener(MouseEvent.MOUSE_UP, reset);
function menuPause(e:Event){
running=false;
currentTime=getTimer();
prevDiff+=diff;
}
function menuPlay (e:Event){
running=true;
}
function reset(){
running=true;
prevDiff+=9000;
}
A little explaination on code:
getTimer() returns the miliseconds from when you opened the app and
You can't Pause "getTimer()"
but you can get the time that game is paused and subtract from getTimer().
variable "diff" does that here.
and "currentTime" is when you paused the game.
Andre's answer is more easy;
my answer is more accurate.
because getTimer() returns real miliseconds but timer is not ticking exactly accurate.ENTER_FRAME event and setInterval are also same as timer.
that means if you want a more simple code, use Andre's and if you want an accurate Timer, use Mine.
and removing eventListener (3vilguy's answer) is not enough
because getTimer won't Pause !
I hope my answer be useful.
Better using the Timer- Object
var seconds=9;
var t:Timer=new Timer(1000,seconds);
t.addEventListener(TimerEvent.TIMER, updateTimer);
t.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
updateTimer();
t.start();
function updateTimer(e:TimerEvent=null){
var t:uint = t.currentCount;
var dt:uint = seconds - t;
var totseconds:uint = dt;
var minutes:uint = Math.floor(totseconds/60);
var sec:uint = Math.floor(totseconds%60);
var minsWithZ = minutes < 10 ? "0" + minutes : minutes;
var secsWithZ = sec < 10 ? "0" + sec : sec;
var time = minsWithZ + ":" + secsWithZ;
this.tempo_txt.text = time;
}
function timerCompleteHandler(e:TimerEvent):void{
trace("Timer complete");
}
pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);
function menuPause(e:MouseEvent){
t.stop();
voltar.addEventListener(MouseEvent.MOUSE_UP, play);
}
function play (e:MouseEvent){
t.start();
}
Greetings

Countdown timer not working in AS3

Since Im new in AS3 and I just converted AS2 to AS3. The countdown doesnt work. Right now the 4 digits are looping all in the same time very fast (The three digits animation is fine - ignore it)
See countdown - http://magnixsolutions.com/clients/OT/media-buys_scoreboard-redux_160x600_5-8-2009.html
AS3
// get the current date and time as it exists at
// this instance in time when the frame is entered
var currentDate:Date = new Date();
var thisYear:int = currentDate.getFullYear();
var thisMonth:int = currentDate.getMonth();
var thisDate:int = currentDate.getDate();
var thisHour:int = currentDate.getHours();
var thisMinute:int = currentDate.getMinutes();
var thisSecond:int = currentDate.getSeconds() + 12;
var thisMSecond:int = currentDate.getMilliseconds();
// Date( year, month-1, date [, hour [, minute [, second [, millisecond]]]])
var eventDate = new Date(thisYear, thisMonth, thisDate, thisHour, thisMinute, thisSecond, thisMSecond);
var eventMillisecs = eventDate.getTime();
// get the current date and time as it exists at
// this instance in time when the frame is entered
this.addEventListener(TimerEvent.TIMER, enterFrameHandler);
function enterFrameHandler() {
currentDate = new Date();
var currentMillisecs = currentDate.getTime();
this.msecs = eventMillisecs - currentMillisecs;
if (this.msecs <= 0){
play();
return;
}
// if the date hasn't been reached, continue to
// devise seconds, minutes, hours and days from
// the calculated milliseconds
this.secs = Math.floor(this.msecs/1000); // 1000 milliseconds make a second
this.mins = Math.floor(this.secs/60); // 60 seconds make a minute
this.hours = Math.floor(this.mins/60); // 60 minutes make a hour
this.days = Math.floor(this.hours/24); // 24 hours make a second
this.msecs = int(this.msecs % 1000);
this.secs = int(this.secs % 60);
this.mins = int(this.mins % 60);
this.hours = int(this.hours % 24);
this.days = int(this.days);
while (this.msecs.length < 3) this.msecs = "0" + this.msecs;
if (this.secs.length < 2) this.secs = "0" + this.secs;
if (this.mins.length < 2) this.mins = "0" + this.mins;
if (this.hours.length < 2) this.hours = "0" + this.hours;
while (this.days.length < 3) this.days = "0" + this.days;
for(var movie in this){
if (this[movie]._parent == this) this[movie].evaluateFrameFrom(this);
}
};
MovieClip.prototype.evaluateFrameFrom = function(variableClip){
var nameArray = this._name.split("_");
var numberSet = variableClip[nameArray[0]];
var character:int = parseInt(nameArray[1]);
var frame = 1 + parseInt(numberSet.charAt(character));
if (this._currentframe != frame) this.gotoAndStop(frame);
};
This is probably what you mean:
// There is no number type in AS3. Use parseInt to cast string to int
var character:int = parseInt(nameArray[1]);
var frame = 1 + parseInt(numberSet.charAt(character));
Also, there's no such thing as _root in ActionScript 3.0. Try this:
this.avgscore_mc.gotoAndPlay(2);
And you need to add your enterFrame like this:
this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
function enterFrameHandler() {
// Stuff in your enter frame
}
Sounds like you're still thinking AS 2.0!

Action Script 3. Restore timer to 0 after game restart

I'm creating flash game, here is timer which counts how long player playing at current level. And here is "Restart" button, I need to restart timer (count from 0) after this button is clicked.
Here is my timer's code:
public function MemoryGame()
{
addChild(CardContainer);
tryAgain.addEventListener(MouseEvent.CLICK, restartGame);
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
txtTime = new TextField();
addChild(txtTime);
tmpTime = timer.currentCount;
timer.start();
}
private function tick(e:Event):void {
txtTime.text = showTimePassed(timer.currentCount - tmpTime);
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0xFF0000;
format.size = 16;
format.bold = true;
//txtTime.x = 250;
txtTime.width/2;
var stageCenter_x:Number = stage.stageWidth/2;
var stageCenter_y:Number = stage.stageHeight/2;
var textCenter_x:Number = txtTime.width/2;
var textCenter_y:Number = txtTime.height/2;
txtTime.x = stageCenter_x - textCenter_x;
txtTime.autoSize = TextFieldAutoSize.CENTER;
txtTime.defaultTextFormat = format;
}
function showTimePassed(startTime:int):String {
var leadingZeroMS:String = ""; //how many leading 0's to put in front of the miliseconds
var leadingZeroS:String = ""; //how many leading 0's to put in front of the seconds
var leadingZeroM:String = "";
var time = getTimer() - startTime; //this gets the amount of miliseconds elapsed
var miliseconds = (time % 1000); // modulus (%) gives you the remainder after dividing,
if (miliseconds < 10) { //if less than two digits, add a leading 0
leadingZeroMS = "0";
}
var seconds = Math.floor((time / 1000) % 60); //this gets the amount of seconds
if (seconds < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroS = "0";
}
var minutes = Math.floor((time / (60 * 1000) ) );
if (minutes < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroM = "0";
}
//60 seconds times 1000 miliseocnds gets the minutes
return leadingZeroM + minutes + ":" + leadingZeroS + seconds + "" + leadingZeroMS ;
}
When I use: removeChild(txtTime); and later addChild(txtTime); timer not restarting just removing for the time, later adding again and continue time counting. How to restore timer to 0? Any ideas? Thank you very much.
EDIT:
Timer must resets when restartGame() function is used.
When I use this - nothing happens.
public function MemoryGame()
{
addChild(CardContainer);
tryAgain.addEventListener(MouseEvent.CLICK, restartGame);
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
timer.addEventListener(TimerEvent.TIMER, resetTimer);
txtTime = new TextField();
addChild(txtTime);
tmpTime = timer.currentCount;
timer.start();
}
function restartGame(e:MouseEvent):void
{
timer.addEventListener(TimerEvent.TIMER, resetTimer);
}
function resetTimer(event:TimerEvent):void{
timer.reset();
timer.start();
}
When I use this - timer stops and continue counting, but not reseting.
function restartGame(e:MouseEvent):void
{
timer.reset();
timer.start();
}
What's wrong?
You can use
timer.reset();
to reset it and then start it again with:
timer.start();
See docs for more info