var HelloWorldLayer = cc.Layer.extend({ ctor:function () { this._super(); cc.log("HelloWorld init"); var size = cc.director.getWinSize(); var bg = new cc.Sprite(res.Background_png); bg.x = size.width/2; bg.y = size.height/2; this.addChild(bg, 0, 0); var ball = new cc.Sprite(res.Ball_png); ball.x = size.width/2; ball.y = size.height/2; this.addChild(ball, 10, SpriteTags.kBall_Tag); return true; }, onEnter: function () { this._super(); cc.log("HelloWorld onEnter"); var ball = this.getChildByTag(SpriteTags.kBall_Tag); cc.inputManager.setAccelerometerEnabled(true); ① cc.eventManager.addListener({ ② event: cc.EventListener.ACCELERATION, ③ callback: function(acc, event){ ④ var size = cc.director.getWinSize(); ⑤ var s = ball.getContentSize(); ⑥ var p0 = ball.getPosition(); var p1x = p0.x + acc.x * SPEED ; ⑦ if ((p1x - s.width/2) <0) { ⑧ p1x = s.width/2; ⑨ } if ((p1x + s.width / 2) > size.width) { ⑩ p1x = size.width - s.width / 2; ? } var p1y = p0.y + acc.y * SPEED ; if ((p1y - s.height/2) < 0) { p1y = s.height/2; } if ((p1y + s.height/2) > size.height) { p1y = size.height - s.height/2; } ball.runAction(cc.place(cc.p( p1x, p1y))); ? } }, ball); }, onExit: function () { this._super(); cc.log("HelloWorld onExit"); cc.eventManager.removeListeners(cc.EventListener.ACCELERATION); ? } });上述代码①行开启加速计设备。第②行代码cc.eventManager.addListener是通过快捷方式注册事件监听器对象。第③行代码是设置加速度事件cc.EventListener.ACCELERATION。第④行代码是设置加速度事件回调函数。第⑤行代码是获得屏幕的大小。第⑥行代码是获得小球的大小。
上述onExit()函数是退出层时候回调,我们在代码第?行注销所有加速度事件的监听。
《Cocos2d-x实战 JS卷》现已上线,各大商店均已开售:
京东:http://item.
原文地址:http://blog.csdn.net/tonny_guan/article/details/44851983