HTML5 게임 프레임워크 cnGameJS 개발 기록 - 게임 장면 객체

黄舟
풀어 주다: 2017-03-24 15:58:24
원래의
2119명이 탐색했습니다.

1. 장면 객체 는 언제 필요한가요?

씬 객체는 이전 글에서 소개한 지도 객체와는 다르며, 다양한 종류의 게임에서 사용됩니다. 이전 맵 개체는 Sokoban 및 Tank Battle과 같은 그리드 게임에서 사용되었습니다. 이 섹션에서 소개하는 장면 개체는 Super Mario, Dinosaur Kombat 등과 같이 특정 장면이 있는 게임에 적합합니다. 이러한 유형의 게임은 일반적으로 2D 장면에서 플레이어 개체를 제어합니다. 플레이어가 움직이면 장면도 그에 따라 움직입니다.

2. 장면 예:

효과: (왼쪽 및 오른쪽 키로 슈퍼 마리오의 움직임을 제어)

HTML5 게임 프레임워크 cnGameJS 개발 기록 - 게임 장면 객체


코드:

<body>
<div><canvas id="gameCanvas">请使用支持canvas的浏览器查看</canvas></div>
</body>
<script src="cnGame_v1.0.js"></script>
<script>
var Src="http://images.cnblogs.com/cnblogs_com/Cson/290336/o_player.png";
var background="background.png";

/* 初始化 */
cnGame.init(&#39;gameCanvas&#39;,{width:500,height:400});
var floorY=cnGame.height-40;
var gameObj=(function(){
    /* 玩家对象 */
    var player=function(options){
        this.init(options);    
        this.speedX=0;
        this.moveDir;
        this.isJump=false;
    }
    cnGame.core.inherit(player,cnGame.Sprite);
    player.prototype.initialize=function(){
        this.addAnimation(new cnGame.SpriteSheet("playerRight",Src,{frameSize:[50,60],loop:true,width:150,height:60}));
        this.addAnimation(new cnGame.SpriteSheet("playerLeft",Src,{frameSize:[50,60],loop:true,width:150,height:120,beginY:60}));
    }
    player.prototype.moveRight=function(){
        if(cnGame.core.isUndefined(this.moveDir)||this.moveDir!="right"){
            this.moveDir="right";
            this.speedX<0&&(this.speedX=0);
            this.setMovement({aX:10,maxSpeedX:15});
            this.setCurrentAnimation("playerRight");
        }
    }
    player.prototype.moveLeft=function(){
        if(cnGame.core.isUndefined(this.moveDir)||this.moveDir!="left"){
            this.moveDir="left";
            this.speedX>0&&(this.speedX=0);
            this.setMovement({aX:-10,maxSpeedX:15});
            this.setCurrentAnimation("playerLeft");
        }
    }
    player.prototype.stopMove=function(){
        
        if(this.speedX<0){
            this.setCurrentImage(Src,0,60);
        }
        else if(this.speedX>0){
            this.setCurrentImage(Src);
        }    
    
        this.moveDir=undefined;
        this.resetMovement();
        
        
    }
    player.prototype.update=function(){
        player.prototype.parent.prototype.update.call(this);//调用父类update
if(cnGame.input.isPressed("right")){
            this.moveRight();    
        }
        else if(cnGame.input.isPressed("left")){
            this.moveLeft();
        }
        else{
            this.stopMove();
        }
        
        
    }

    return {
        initialize:function(){
            cnGame.input.preventDefault(["left","right","up","down"]);
            this.player=new player({src:Src,width:50,height:60,x:0,y:floorY-60});
            this.player.initialize();
            this.background=new cnGame.View({src:background,player:this.player,imgWidth:2301});
            this.background.centerPlayer(true);
            this.background.insideView(this.player,"x");
        },
        update:function(){
            this.player.update();
            this.background.update([this.player]);
        },
        draw:function(){
            this.background.draw();
            this.player.draw();
            
        }

    };
})();
cnGame.loader.start([Src,background],gameObj);
</script>
로그인 후 복사

3. 코드 구현:
장면을 구성하려면 먼저 충분히 넓은 배경 그림 이 필요합니다. 플레이어가 오른쪽으로 이동할 때 플레이어는 항상 배경의 중간 지점에 있습니다. 플레이어의 속도는 반대 방향의 배경으로 변환됩니다. 먼저 초기화 함수 를 살펴보세요.

/**
         *初始化
        **/
        init:function(options){
            /**
             *默认对象
            **/
            var defaultObj={
                width:cg.width,
                height:cg.height,
                imgWidth:cg.width,
                imgHeight:cg.height,
                x:0,
                y:0
                
            }
            options=options||{};
            options=cg.core.extend(defaultObj,options);
            this.player=options.player;
            this.width=options.width;
            this.height=options.height;
            this.imgWidth=options.imgWidth;
            this.imgHeight=options.imgHeight;
            this.centerX=this.width/2;
            this.src=options.src;
            this.x=options.x;
            this.y=options.y;
            this.insideArr=[];
            this.isLoop=false;;
            this.isCenterPlayer=false;
            this.onEnd=options.onEnd;
            
        },
로그인 후 복사

xy와 크기 외에도 사용자가 전달하는 매개변수에는 세 가지 매개변수가 있는데, 그 중 하나는 플레이어 개체를 배치할지 여부를 설정하는 것입니다. 중앙에 있고 플레이어를 움직이지 않고 배경만 움직입니다. 위의 배경 이동 효과를 얻으려면 이 매개변수를 true로 설정해야 합니다. 또 다른 매개변수는 루프 여부를 설정하는 것입니다. 루프로 설정하면 배경이 극점으로 이동한 후 원래 위치로 돌아갑니다. 마지막 매개변수는 onEnd입니다. 비순환으로 설정하면 배경이 극한으로 이동한 후 콜백 함수가 실행됩니다.

장면 개체의 초점은 업데이트 방법입니다.

/**
         *背景移动时的更新
        **/
        update:function(spritelist){//传入所有sprite的数组
            if(this.isCenterPlayer){
                if(this.player.x>this.centerX){
                    if(this.x<this.imgWidth-this.width){
                        var marginX=this.player.x-this.centerX;    
                        this.x+=marginX;
                        if(spritelist){
                            for(var i=0,len=spritelist.length;i<len;i++){
                                if(spritelist[i]==this.player){
                                    spritelist[i].x=this.centerX;
                                }
                                else{
                                    spritelist[i].x-=marginX;    
                                }
                            }
                        }
                    }
                    else if(this.isLoop){
                        if(spritelist){
                            for(var i=0,len=spritelist.length;i<len;i++){
                                if(spritelist[i]!=this.player){
                                    spritelist[i].move(this.imgWidth-this.width);
                                }
                            }
                        }
                        this.x=0;
                    }
                    else{
                        this.onEnd&&this.onEnd();
                    }
                }
            }
            for(var i=0,len=this.insideArr.length;i<len;i++){
                inside.call(this,this.insideArr[i]);
            }
        },
로그인 후 복사

이 방법은 먼저 플레이어 개체가 장면의 중심을 초과했는지 여부를 확인합니다. 거리를 초과하여 플레이어를 고정합니다. 장면 중앙에서 초과 거리는 반대 방향으로 이동하는 배경과 플레이어를 제외한 다른 스프라이트가 반대 방향으로 이동하는 거리로 설정됩니다. 이 경우 배경만 설정됩니다. 이동 및 기타 스프라이트 개체가 이동하고 플레이어는 고정됩니다 . 루프인 경우 이동 범위를 초과한 후 배경 및 기타 스프라이트의 x 좌표를 재설정합니다. 루프가 아닌 경우 이동이 끝난 후 onEnd 콜백 함수가 호출됩니다. 또한 플레이어가 항상 디스플레이 영역 내에 있도록 제한해야 하는 경우 insideView 메서드를 호출할 수도 있습니다.

장면 객체의 모든 코드를 첨부하세요:

/**
 *
 *场景
 *
**/
cnGame.register("cnGame",function(cg){
    
    /**
     *使指定对象在可视区域view内
    **/
    var inside=function(sprite){
        var dir=sprite.insideDir;
        if(dir!="y"){
            if(sprite.x<0){
                sprite.x=0;
            }
            else if(sprite.x>this.width-sprite.width){
                sprite.x=this.width-sprite.width;
            }
        }
        if(dir!="x"){
            if(sprite.y<0){
                sprite.y=0;
            }
            else if(sprite.y>this.height-sprite.height){
                sprite.y=this.height-sprite.height;
            }
        }
            
    }
    
    var view=function(options){
        this.init(options);
        
    }
    view.prototype={
    
        /**
         *初始化
        **/
        init:function(options){
            /**
             *默认对象
            **/
            var defaultObj={
                width:cg.width,
                height:cg.height,
                imgWidth:cg.width,
                imgHeight:cg.height,
                x:0,
                y:0
                
            }
            options=options||{};
            options=cg.core.extend(defaultObj,options);
            this.player=options.player;
            this.width=options.width;
            this.height=options.height;
            this.imgWidth=options.imgWidth;
            this.imgHeight=options.imgHeight;
            this.centerX=this.width/2;
            this.src=options.src;
            this.x=options.x;
            this.y=options.y;
            this.insideArr=[];
            this.isLoop=false;;
            this.isCenterPlayer=false;
            this.onEnd=options.onEnd;
            
        },
        /**
         *使player的位置保持在场景中点之前的移动背景
        **/
        centerPlayer:function(isLoop){
            isLoop=isLoop||false;
            this.isLoop=isLoop;
            this.isCenterPlayer=true;
        },
        /**
         *使对象的位置保持在场景内
        **/
        insideView:function(sprite,dir){//dir为限定哪个方向在view内,值为x或y,不传则两个方向皆限定
            if(cg.core.isArray(sprite)){
                for(var i=0,len=sprite.length;i
로그인 후 복사

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

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!