间隔循环执行

发表于2017-03-09
评论0 3k浏览

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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(1136640, WebGL);
                         
                        Laya.stage.bgColor = "#ffffff";
                         
                        //以500毫秒的时间间隔播放颜色切换的矩形
                        Laya.timer.loop(500this, createRect);
                         
                }
                 
                private function createRect():void
                {
                        var c:Sprite = new Sprite(); 
                        var color:String = (flag = !flag)?"#A52A2A":"#FFA500"
                        c.graphics.clear();
                        c.graphics.drawRect(5050300100, color);
                        Laya.stage.addChild(c);
                }
         
        }
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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(1136640, WebGL);
                         
                        Laya.stage.bgColor = "#ffffff";
                         
                        //以30帧为间隔播放颜色切换的矩形
                        Laya.timer.frameLoop(30this, createRect);
                         
                }
                 
                private function createRect():void
                {
                        var c:Sprite = new Sprite(); 
                        var color:String = (flag = !flag)?"#A52A2A":"#FFA500"
                        c.graphics.clear();
                        c.graphics.drawRect(5050300100, color);
                        Laya.stage.addChild(c);
                }
         
        }
}


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


    


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

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引