Home  >  Article  >  Web Front-end  >  HTML5 game framework cnGameJS development record-game loop

HTML5 game framework cnGameJS development record-game loop

黄舟
黄舟Original
2017-03-25 15:08:061741browse

Since the entire game occurs in a game loop, the game loop can be said to be the core part of the game. Every time it loops, update the properties of the game object and draw the game elements.

As mentioned in the previous resource loading article, after the resource loading is completed, a game loop will be started when starting the game. Now let’s review this part of the code:

/**
     *图像加载完毕的处理程序
    **/    
    var imgLoad=function(self){
        return function(){
            self.loadedCount+=1;
            self.loadedImgs[this.srcPath]=this;
            this.onLoad=null;                    //保证图片的onLoad执行一次后销毁
            self.loadedPercent=Math.floor(self.loadedCount/self.sum*100);
            self.onLoad&&self.onLoad(self.loadedPercent);
            if(self.loadedPercent===100){
                self.loadedCount=0;
                self.loadedPercent=0;
                loadingImgs={};
                if(self.gameObj&&self.gameObj.initialize){
                    self.gameObj.initialize();
                    if(cg.loop&&!cg.loop.stop){//结束上一个循环
                        cg.loop.end();
                    }
                    cg.loop=new cg.GameLoop(self.gameObj);//开始新游戏循环
                    cg.loop.start();
                }
                
            }
            
        
        }
    }

After the image resources are loaded, call the initialize method of the game object and determine whether the game loop object exists. If it exists, end the previous loop (this situation usually occurs when switching levels and passing in new game objects), otherwise it is established. and start the game loop.

Okay, now let’s take a look at the implementation code of the game loop:

var gameLoop=function(gameObj,options){
    
        if(!(this instanceof arguments.callee)){
            return new arguments.callee(gameObj,options);
        }
        this.init(gameObj,options);    
    }

First of all, the game loop function must also be guaranteed to be constructor Called in the form, after the call, initialize the object:

/**
         *初始化
        **/
        init:function(gameObj,options){
            /**
             *默认对象
            **/    
            var defaultObj={
                fps:30
            };
            options=options||{};
            
            options=cg.core.extend(defaultObj,options);
            this.gameObj=gameObj;
            this.fps=options.fps;
            interval=1000/this.fps;
            
            this.pause=false;
            this.stop=true;
        },

There is only one parameter that the user needs to set, which is fps (frame per second). This parameter is the number of frames executed per second. According to this parameter , we can calculate how many milliseconds to execute the game loop (interval parameter). In addition, the loop supports two modes: pause and stop.

/**
         *开始循环
        **/    
        start:function(){
            if(this.stop){        //如果是结束状态则可以开始
                this.stop=false;
                
                this.now=new Date().getTime();
                this.startTime=new Date().getTime();
                this.duration=0;    
                loop.call(this)();    
            }    
        },

When the loop starts, we can save the start time so that the duration of the loop can be continuously updated. Then call the loop function to implement the loop.

var timeId;
    var interval;
    /**
    *循环方法
    **/    
    var loop=function(){
        var self=this;
        return function(){
            if(!self.pause&&!self.stop){
                
                self.now=new Date().getTime();
                self.duration=self.startTime-self.now;
                
                if(self.gameObj.update){
                    self.gameObj.update();
                }
                if(self.gameObj.draw){
                    cg.context.clearRect(0,0,cg.width,cg.height);
                    self.gameObj.draw();
                }
            }
            timeId=window.setTimeout(arguments.callee,interval);
        }
    }

If it is not paused or stopped, the update and draw of the game object are called (note that the update of the game object is responsible for calling the update of all elements of the level, and the same is true for draw). Then call setTimeoutRecursivelyCall yourself to implement a loop.

Game loop all source code:

/**
 *
 *游戏循环
 *
**/
cnGame.register("cnGame",function(cg){

    var timeId;
    var interval;
    /**
    *循环方法
    **/    
    var loop=function(){
        var self=this;
        return function(){
            if(!self.pause&&!self.stop){
                
                self.now=new Date().getTime();
                self.duration=self.startTime-self.now;
                
                if(self.gameObj.update){
                    self.gameObj.update();
                }
                if(self.gameObj.draw){
                    cg.context.clearRect(0,0,cg.width,cg.height);
                    self.gameObj.draw();
                }
            }
            timeId=window.setTimeout(arguments.callee,interval);
        }
    }
    
    var gameLoop=function(gameObj,options){
    
        if(!(this instanceof arguments.callee)){
            return new arguments.callee(gameObj,options);
        }
        this.init(gameObj,options);    
    }
    gameLoop.prototype={
        /**
         *初始化
        **/
        init:function(gameObj,options){
            /**
             *默认对象
            **/    
            var defaultObj={
                fps:30
            };
            options=options||{};
            
            options=cg.core.extend(defaultObj,options);
            this.gameObj=gameObj;
            this.fps=options.fps;
            interval=1000/this.fps;
            
            this.pause=false;
            this.stop=true;
        },
            
        /**
         *开始循环
        **/    
        start:function(){
            if(this.stop){        //如果是结束状态则可以开始
                this.stop=false;
                
                this.now=new Date().getTime();
                this.startTime=new Date().getTime();
                this.duration=0;    
                loop.call(this)();    
            }    
        },
        /**
         *继续循环
        **/    
        run:function(){
            this.pause=false;    
        },
        /**
         *暂停循环
        **/    
        pause:function(){
            this.pause=true;    
        },
        /**
         *停止循环
        **/    
        end:function(){
            this.stop=true;
            window.clearTimeout(timeId);
        }
        
        
    }
    this.GameLoop=gameLoop;
});

The above is the detailed content of HTML5 game framework cnGameJS development record-game loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn