1. 程式人生 > >cocoscreator遊戲開發(一) tilemap

cocoscreator遊戲開發(一) tilemap

//下面是完整程式碼



var DIR = cc.Enum({
    UP:0,
    RIGHT:1,
    DOWN:2,
    LEFT:3,
});

cc.Class({
    extends: cc.Component,

    properties: {
        direction:DIR.UP,
        speed:32,
        /*  _____>x
            |
            |
            y
        */
        tileX:0,
        tileY:0,
        
        offsetX:0,
        offsetY:0,


        map:{
            default:null,
            type:cc.TiledMap
        },
        ground:{
            default:null,
            type:cc.TiledLayer,
        },
        barrier:{
            default:null,
            type:cc.TiledLayer,
        },

        upBtn : { default: null,  type: cc.Button},
        rightBtn : { default: null,  type: cc.Button},
        downBtn : { default: null,  type: cc.Button},
        leftBtn : { default: null,  type: cc.Button},
       
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        
        this.tileX = 0;
        this.tileY = 0;
        this.offsetX = -302.4;
        this.offsetY = 223.3;

        this.upBtn.node.on('click', this.btnUp, this);
        this.rightBtn.node.on('click', this.btnRight, this);
        this.downBtn.node.on('click', this.btnDown, this);
        this.leftBtn.node.on('click', this.btnLeft, this);
    },

    start () {

    },

    update (dt) { 
        //顯示層 更新位置
        this.node.x = this.offsetX + this.tileX*32;
        this.node.y = this.offsetY - this.tileY*32;    
    },
    //按鍵響應
    btnUp:function(){
        var next = cc.p(this.tileX,this.tileY-1);
        this.direction = DIR.UP;
        this.checkWalk(next);
    },
    btnRight:function(){
        var next = cc.p(this.tileX+1,this.tileY);
        this.direction = DIR.RIGHT;
        this.checkWalk(next);
    },
    btnDown:function(next){
        var next = cc.p(this.tileX,this.tileY+1);
        this.direction = DIR.DOWN;
        this.checkWalk(next);
    },
    btnLeft:function(next){
        var next = cc.p(this.tileX-1,this.tileY);
       this. direction = DIR.LEFT;
       this.checkWalk(next);
    },

    checkWalk:function(next){
        console.log(next);
        if(this.barrier.getTileGIDAt(next))
        {           
            console.log("block");
            return;
        }
        this.tileX = next.x;
        this.tileY = next.y;
    },


});