最近在写游戏,有个倒计时效果,写个类
import mx.events.EventDispatcher;
import mx.utils.Delegate;
//倒计时
class game.time.Time {
private var _id:Number;
private var _second:Number;
private var _total:Number;
private var dispatchEvent:Function;
public var addEventListener:Function;
public var removeEventListener:Function;
public function Time(s) {
EventDispatcher.initialize(this);
_second = s;
_total = s;
}
public function getTime() {
return _second;
}
private function timeing() {
if (_second>0) {
_second--;
this.dispatchEvent({type:"onPlay", value:_second});
} else {
this.dispatchEvent({type:"onStop", value:_second});
trace("stop")
this.stop();
}
}
public function play() {
_id = setInterval(Delegate.create(this, timeing), 1000);
}
public function stop() {
_second = _total;
clearInterval(_id);
}
}
使用
import game.time.Time;
//倒计时的时间
var _totalTime = 30;
var _time = new Time(_totalTime);
_time.addEventListener("onPlay", timeStart);
_time.addEventListener("onStop", timeOver);
//计时中..
function timeStart(obj) {
time = obj.value;
score = _score;
update();
}
//超时,结束游戏
function timeOver() {
gotoAndStop("over");
}
startBtn.onRelease=function(){
//启动倒计时
_time.play()
}