CocosCreator 물체 이동 제어

1878 단어 CocosCreator
간단하게 실현·상하좌우 네 방향으로 이동하는 스크립트 코드를 썼는데 다음과 같습니다. 마운트는 바로 실행할 수 있습니다.
properties: {
        //      
        MoveSpeed:0,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        //      
        this.left=false;
        this.right=false;
        this.up=false,
        this.down=false;
        
        //         
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,this.onKeyDown,this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP,this.onKeyUp,this);
    },

    start () {
   
    },

    update (dt) {
         //              
         //    
         if(this.left){
             this.node.x-=this.MoveSpeed*dt;
         }else if(this.right){
            this.node.x+=this.MoveSpeed*dt;
         }
         //    
         if(this.down){
            this.node.y-=this.MoveSpeed*dt;
        }else if(this.up){
           this.node.y+=this.MoveSpeed*dt;
        }
    },

    onKeyDown(event){
        //             
        switch(event.keyCode){
            //  A 
            case cc.macro.KEY.a:
              this.left=true;
            break;
            case cc.macro.KEY.d:
              this.right=true;
            break;
            case cc.macro.KEY.w:
              this.up=true;
            break;
            case cc.macro.KEY.s:
              this.down=true;
            break;
        }
    },

    onKeyUp(event){
        //          
        switch(event.keyCode){
            //  A 
            case cc.macro.KEY.a:
              this.left=false;
            break;
            case cc.macro.KEY.d:
              this.right=false;
            break;
            case cc.macro.KEY.w:
              this.up=false;
            break;
            case cc.macro.KEY.s:
              this.down=false;
            break;
        }
    },

8방향의 원리를 실현하려면 차이가 많지 않다. 단지 다른 네 방향으로 이동할 때 x.y축의 좌표를 동시에 바꾸는 것이다.

좋은 웹페이지 즐겨찾기