请参见原作者实现
Cocos2d-x《雷电大战》(2)-精灵随手指移动,你点哪我走哪!
作者想实现的功能是有个飞机,可以接受触控事件,让飞机跟着手指走
1.资源
var res = { //... AIRPLAN:'res/air1.png',//... };
2.添加新的层至HelloScene
var HelloWorldScene = cc.Scene.extend({ onEnter:function () { //.... //可以飞了 var airLayer=new Airplane(); this.addChild(airLayer,300); //.... } });3 project.json中添加新的脚本引用
"jsList" : [ "src/resource.js","src/airplane.js",//我们新的文件 "src/app.js" ]
4现在我们可以在src/airplane.js中实现Airplane了
var Airplane = cc.Sprite.extend({ ctor:function (){ var me=this; var size=cc.winSize; me._super(res.AIRPLAN) me.setPosition(size.width/2,size.height/2); cc.eventManager.addListener(cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE,swallowTouches: true,onTouchBegan: me.onTouchBegan.bind(me),onTouchMoved: me.onTouchMoved.bind(me),onTouchEnded: me.onTouchEnded.bind(me),}),me); return true; },onTouchBegan:function(touch,e){ var me=this; var size=me.getContentSize(); var rect = cc.rect(0,size.width,size.height); var point = me.convertToNodeSpace(touch.getLocation()); if(cc.rectContainsPoint(rect,point)){ me.started=true; return true; } return false; },onTouchMoved:function(touch,e){ var me=this; var size=me.getContentSize(); if(!!me.started){ var delta = touch.getDelta(); var x=me.x + delta.x; var y=me.y + delta.y; if(x <= size.width / 2 ){ x = size.width / 2; }else if(x > cc.winSize.width - size.width /2 ){ x = cc.winSize.width - size.width /2; } if(y < size.height / 2){ y = size.height/2; }else if(y > cc.winSize.height - size.height / 2){ y = cc.winSize.height - size.height / 2 } me.x=x; me.y=y; } },onTouchEnded:function(t,e){ this.started=false; } });