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!

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools