Skip to content

Instantly share code, notes, and snippets.

@fenixkim
Last active December 13, 2015 17:09
Show Gist options
  • Save fenixkim/4945720 to your computer and use it in GitHub Desktop.
Save fenixkim/4945720 to your computer and use it in GitHub Desktop.
This snippet allows create a countdown for milliseconds usefull for games. It must be included into a movieclip which contains a dynamic text field called 'tf'.
import com.greensock.TweenMax;
var now:Date;
var endDate:Date;
var seconds:Number;
var isRunning:Boolean;
var wasInitialized:Boolean;
function updateTime(e:Event):void {
var currentDate:Date = new Date();
var timeLeft:Number = endDate.getTime() - currentDate.getTime();
var milliseconds:Number = timeLeft;
var newSeconds:Number = Math.floor(timeLeft / 1000);
if (seconds != newSeconds && seconds > 0 && seconds <= 6) {
// Poner sonido de terror aquí
TweenMax.to(tf, 0, {textColor:0xff0000});
TweenMax.to(tf, 0, {textColor:0xffffff, delay:0.5});
}
seconds = Math.floor(timeLeft / 1000);
milliseconds %= 1000;
seconds %= 60;
var ms:String = milliseconds.toString().substr(0, 2);
//var ms:String = Math.round(milliseconds/10).toString();
var sec:String = seconds.toString();
if (sec.length < 2) {
sec = "0" + sec;
}
var time:String = sec + "." + ms;
tf.text = time;
if (seconds < 0) {
removeEventListener(Event.ENTER_FRAME, updateTime);
setText("00.00");
wasInitialized = false;
trace("Finished!");
}
}
function startTimerFrom(endSeconds:int) {
stopTimer();
isRunning = true;
wasInitialized = true;
now = new Date();
endDate = new Date(now.fullYear, now.month, now.date, now.hours, now.minutes, now.seconds + endSeconds);
addEventListener(Event.ENTER_FRAME, updateTime);
}
function resumeTimer() {
if (wasInitialized) {
isRunning = true;
addEventListener(Event.ENTER_FRAME, updateTime);
}
}
function stopTimer() {
isRunning = false;
removeEventListener(Event.ENTER_FRAME, updateTime);
}
function addSecondsToTimer(seconds:int) {
stopTimer();
endDate = new Date(endDate.fullYear, endDate.month, endDate.date, endDate.hours, endDate.minutes, endDate.seconds + seconds);
resumeTimer();
}
function setText(text:String) {
tf.text = text;
}
//startTimerFrom(30);
@fenixkim
Copy link
Author

Require:

  • TweenMax
  • Flash Timeline based project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment