ActionScript
TypeScript
JavaScript

间隔循环执行

发布时间:2017-03-08

        时钟管理类laya.utils.Timer中关于间隔循环执行有两种方法,分别为按时间循环执行loop()和按帧率循环执行frameLoop()。这两种方法理解起来比较简单,我们直接看下API参数说明,如下图所示:

loop按时间循环执行示例代码:

package
{
        import laya.display.Sprite;
        import laya.display.Text;
        import laya.webgl.WebGL;

        public class TimerDEMO
        {
                private var flag:Boolean;
                
                public function TimerDEMO()
                {
                        Laya.init(1136, 640, WebGL);
                        
                        Laya.stage.bgColor = "#ffffff";
                        
                        //以500毫秒的时间间隔播放颜色切换的矩形
                        Laya.timer.loop(500, this, createRect);
                        
                }
                
                private function createRect():void
                {
                        var c:Sprite = new Sprite(); 
                        var color:String = (flag = !flag)?"#A52A2A":"#FFA500"
                        c.graphics.clear();
                        c.graphics.drawRect(50, 50, 300, 100, color);
                        Laya.stage.addChild(c);
                }
        
        }
}

frameLoop按帧率循环执行示例代码:

package
{
        import laya.display.Sprite;
        import laya.display.Text;
        import laya.webgl.WebGL;

        public class TimerDEMO
        {
                private var flag:Boolean;
                
                public function TimerDEMO()
                {
                        Laya.init(1136, 640, WebGL);
                        
                        Laya.stage.bgColor = "#ffffff";
                        
                        //以30帧为间隔播放颜色切换的矩形
                        Laya.timer.frameLoop(30, this, createRect);
                        
                }
                
                private function createRect():void
                {
                        var c:Sprite = new Sprite(); 
                        var color:String = (flag = !flag)?"#A52A2A":"#FFA500"
                        c.graphics.clear();
                        c.graphics.drawRect(50, 50, 300, 100, color);
                        Laya.stage.addChild(c);
                }
        
        }
}


两个示例的运行效果基本相同,如下面的动图所示,一直保持循环执行:

gaollg0.GIF

        两种相同之处是都以周期间隔进行循环执行,不同之处为:Loop()方法以毫秒的时间为周期间隔,frameLoop()方法以帧率为周期间隔。由于游戏帧率在不同设备上的不稳定性,当播放帧动画等情况时,采用按帧率定时会更准确一些。