无边框限制的左右移动
cc.Class({ extends: cc.Component, properties: { //speed accl:0, player:{ default:null, type:cc.Node }//}, }, // LIFE-CYCLE CALLBACKS: SetInputControl:function () { var self=this;//先保存一下this,为self //监听 var listener={ //event:cc.eventListener.KEYBOARD,//监听键盘 event:cc.EventListener.KEYBOARD,//监听键盘 //有两个需要监听的方法 onKeyPressed:function (KeyCode,event) { // switch监听 KeyCode键盘摁下 switch (KeyCode) { case cc.KEY.a: self.accLeft=true; break; case cc.KEY.d: self.accRight=true; break; case cc.KEY.w: self.accUp=true; break; case cc.KEY.s: self.accDown=true; break; } },//onKeyReleased onKeyReleased:function (KeyCode,event) { switch (KeyCode) { case cc.KEY.a: self.accLeft=false; break; case cc.KEY.d: self.accRight=false; break; case cc.KEY.w: self.accUp=false; break; case cc.KEY.s: self.accDown=false; break; } }//}, } //将监听放在事件 cc.eventManager.addListener(listener,self.node); }, onLoad :function() { //Init contorl Dircetion this.accLeft=false; this.accRight=false; this.accUp=false; this.accDown=false; this.SetInputControl(); }, start :function() { }, update:function (dt) { //若是利用else 则4个方向;需要为8个方向 if(this.accLeft) { this.player.x -= this.accl; } if(this.accRight) { this.player.x += this.accl; } if(this.accUp) { this.player.y += this.accl; } if(this.accDown) { this.player.y -= this.accl; } } , });
不积跬步,无以至千里;不积小流,无以成江海。