在拖动小游戏的逻辑里,主要看被拖动物体是否拖动到了指定的区域,是则加入到指定区域(换父节点),否则返回原位置!
效果展示
这里只做了一个,其实只要禁止了吞噬触摸,那么可以做任意个物体(不论物体是否存在重叠区域)的拖动操作
- 创建物体和待拖动区域(如果需要大量的待拖动物体,建议使用预制体生成的方式)
- code
cc.Class({
extends: cc.Component,
properties: {
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
this.pokePos = cc.v2(-400,-200);
this.poke = this.node.getChildByName('poke');
this.endBox = this.node.getChildByName('endBox');
this.poke.setPosition(this.pokePos.x,this.pokePos.y);
this.node.on("touchstart",this.touchStart,this);
this.node.on("touchmove",this.touchMove,this);
this.node.on("touchend",this.touchEnd,this);
},
touchStart(event){
let touchPos = event.getLocation();
let posInNode = this.worldConvertLocalPoint(this.poke,touchPos);
let target = this.poke.getContentSize();
let rect = cc.rect(0,0,target.width,target.height);
if(rect.contains(posInNode)){
this.touchTile = this.poke;
}
cc.log(posInNode);
// cc.log(event.getLocation());
},
touchMove(event){
if(this.touchTile){
this.touchTile.setPosition(this.touchTile.x+event.getDelta().x,this.touchTile.y+event.getDelta().y)
}
},
touchEnd(event){
let touchPos = this.touchTile.convertToWorldSpaceAR(cc.v2(0,0));
let posInNode = this.worldConvertLocalPoint(this.endBox,touchPos);
let target = this.endBox.getContentSize();
let rect = cc.rect(0,0,target.width,target.height);
if(rect.contains(posInNode)){
cc.log('-------endPos')
}else{
cc.log('--------goBack');
let action = cc.moveTo(0.3,this.pokePos);
this.touchTile.runAction(action);
}
this.touchTile = null;
},
worldConvertLocalPoint(node, worldPoint) {
if (node) {
return node.convertToNodeSpace(worldPoint);
}
return null;
},
start () {
},
// update (dt) {},
});
- 将脚本挂载在节点上
end