Home Web Front-end H5 Tutorial HTML5 game framework cnGameJS development record-game loop

HTML5 game framework cnGameJS development record-game loop

Mar 25, 2017 pm 03:08 PM

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();
                }
                
            }
            
        
        }
    }
Copy after login

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);    
    }
Copy after login

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;
        },
Copy after login

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)();    
            }    
        },
Copy after login

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);
        }
    }
Copy after login

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;
});
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1228
24
Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

See all articles