>  기사  >  웹 프론트엔드  >  HTML5 게임 프레임워크 cnGameJS 개발 기록 - 게임 루프

HTML5 게임 프레임워크 cnGameJS 개발 기록 - 게임 루프

黄舟
黄舟원래의
2017-03-25 15:08:061682검색

게임 전체가 게임 루프에서 진행되기 때문에 게임 루프는 게임의 핵심이라고 할 수 있습니다. 루프를 실행할 때마다 게임 개체의 속성이 업데이트되고 게임 요소가 그려집니다.

이전 리소스 로딩 기사에서 언급했듯이 리소스 로딩이 완료된 후 게임을 시작할 때 게임 루프가 시작됩니다. 이제 코드의 이 부분을 검토해 보겠습니다.

/**
     *图像加载完毕的处理程序
    **/    
    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();
                }
                
            }
            
        
        }
    }

이미지 리소스가 로드된 후 게임 개체의 초기화 메서드를 호출하고 게임 루프 개체가 존재하는지 확인합니다. 존재하는 경우 이전 루프를 종료합니다(이 상황은 일반적으로 레벨을 전환하고 새 게임 개체를 전달할 때 발생합니다). 그렇지 않으면 게임 루프가 시작됩니다.

좋습니다. 이제 게임 루프의 구현 코드를 살펴보겠습니다.

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

우선 게임 루프 함수 도 이를 기반으로 하는지 확인해야 합니다. 생성자 에서 호출 후 개체를 초기화합니다.

/**
         *初始化
        **/
        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;
        },

사용자가 설정해야 하는 매개변수는 fps(초당 프레임 수) 단 하나뿐입니다. 이 매개변수는 초당 실행되는 프레임 수입니다. 이 매개변수에 따라 게임 루프를 실행하는 데 몇 밀리초가 소요되는지 계산할 수 있습니다(간격 매개변수). 또한 루프는 일시 중지와 중지의 두 가지 모드를 지원합니다.

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

루프가 시작되면 시작 시간을 저장하여 루프 지속 시간을 지속적으로 업데이트할 수 있습니다. 그런 다음 루프 함수를 호출하여 루프를 구현합니다.

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);
        }
    }

일시 중지되거나 중지되지 않으면 게임 개체의 업데이트 및 그리기가 호출됩니다. (게임 개체의 업데이트는 레벨의 모든 요소 업데이트를 호출하는 역할을 담당하며, 무승부는 사실입니다). 그런 다음 setTimeout을재귀적으로호출하여 자신을 호출하여 루프를 구현합니다.

게임루프 전체 소스코드 :

/**
 *
 *游戏循环
 *
**/
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;
});

위 내용은 HTML5 게임 프레임워크 cnGameJS 개발 기록 - 게임 루프의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.