0
点赞
收藏
分享

微信扫一扫

Egret Engine(五):时间控制-计时器


计时器

/**
* Timer 计时器
*/
class TimerDemo extends egret.DisplayObjectContainer {
public constructor() {
super();
//创建一个计时器对象
const timer: egret.Timer = new egret.Timer(1000, 5); // 毫秒 执行次数
//注册事件侦听器
timer.addEventListener(egret.TimerEvent.TIMER, this.timerFunc, this); // 监听执行事件
timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, this.timerComFunc, this); // 监听执行完成事件
//开始计时
timer.start();
}
private timerFunc() {
console.log("计时");
}
private timerComFunc() {
console.log("计时结束");
}
}

new TimerDemo(); // 执行

​Ticker 心跳​​​ 和 ​​帧事件​

  • 对比:​​回调函数调取速率不同​
  • startTick(停止对应stopTick)全局函数将以 60 帧速率回调函数。startTick是定时回调,改变帧率也不会影响回调速度。
  • 帧事件 ENTER_FRAME 是每帧回调,改变帧率会改变回调速度;

实现代码

  • 配置帧率

// 帧率 2帧对比明显
this.stage.frameRate = 2;

  • Ticker 心跳

/**
* Ticker 心跳
* startTick(停止对应stopTick)全局函数将以 60 帧速率回调函数。startTick是定时回调,改变帧率也不会影响回调速度。
*/
class TimerDemo01 extends egret.DisplayObjectContainer {
public constructor() {
super();
this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
}

private star: egret.Bitmap = new egret.Bitmap(RES.getRes("star_png"));
private speed: number = 0.05;
private time: number = 0;

private onLoad(event: egret.Event) {
this.addChild(this.star);
this.time = egret.getTimer();
egret.startTick(this.moveStar, this); // 注册并启动一个计时器,通常会以60FPS的速率触发回调方法,并传入当前时间戳。
}

/**
* 时间戳
*/
private moveStar(timeStamp: number): boolean {

const now = timeStamp;
const pass = now - this.time;

console.log("moveStar: ", (1000 / pass).toFixed(5), pass); // 帧率

this.star.x += this.speed * pass;

this.star.y = 10;

this.time = now;

if (this.star.x > 300) {
egret.stopTick(this.moveStar, this); // 注意:计时器注册后将会持续触发回调方法,若要停止回调,需要手动调用stopTick()方法。
}

return false;

}

}

  • 帧事件

/**
* 帧事件 默认30帧
* ENTER_FRAME 是每帧回调,改变帧率会改变回调速度;
*/
class TimerDemo02 extends egret.DisplayObjectContainer {
public constructor() {
super();
this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
}

private star: egret.Bitmap = new egret.Bitmap(RES.getRes("star_png"));
private speed: number = 0.05;
private time: number = 0;

private onLoad(event: egret.Event) {
this.addChild(this.star);
this.addEventListener(egret.Event.ENTER_FRAME, this.moveStar, this);
this.time = egret.getTimer();
}

private moveStar(e: egret.Event) {
const now = egret.getTimer();
const pass = now - this.time;

console.log("frameRateMoveStar: ", (1000 / pass).toFixed(5), pass); // 帧率

this.star.x += this.speed * pass;
this.star.y = 150;

this.time = now;

if (this.star.x > 300) {
this.removeEventListener(egret.Event.ENTER_FRAME, this.moveStar, this);
}

}
}

对比展示


举报

相关推荐

0 条评论