CocosCreator的拖动小游戏主要逻辑

这篇博客介绍了如何在Unity3D中实现物体拖动和判断拖动到指定区域的功能。通过监听触摸事件,动态更新物体位置,并在触摸结束时检查物体是否位于目标区域内。如果在区域内,则移动物体到该区域,否则返回原位置。这种方法可以应用于多个物体的拖动操作,且不受物体重叠的影响。
摘要由CSDN通过智能技术生成
在拖动小游戏的逻辑里,主要看被拖动物体是否拖动到了指定的区域,是则加入到指定区域(换父节点),否则返回原位置!

效果展示
拖动

这里只做了一个,其实只要禁止了吞噬触摸,那么可以做任意个物体(不论物体是否存在重叠区域)的拖动操作
  • 创建物体和待拖动区域(如果需要大量的待拖动物体,建议使用预制体生成的方式)
    创建物体和待拖动区域
  • 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
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蟹 !

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值