cocos拖拽物体不同实现方式研究

第一种方式:

    onElMove(event:EventTouch){
        console.info("onMove");
        this.e1.setWorldPosition(event.getUILocation().x,event.getUILocation().y,0);
    }

这种方式有缺陷,因为当手指落下时,点击的位置不是Node的中心位置时,移动前会出现一个跳跃的行为,这种使得操作不连贯,效果很不好。

第二种方式: 通过偏移量(getUIDelta)来决定Node的位置,这种才是最好的方式 。

cc.Class({
    extends: cc.Component,
 
    start() {
        // 获取DragonBones实例
        this.dragonBonesNode = this.getComponent(cc.DragonBonesComponent);
        // 获取节点的collider组件
        this.collider = this.node.getComponent(cc.Collider);
        // 如果没有collider组件,则添加一个box collider
        if (!this.collider) {
            this.collider = this.node.addComponent(cc.BoxCollider);
        }
        // 注册触摸事件
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    },
 
    onTouchStart(event) {
        // 记录开始触摸的位置
        this.startPos = event.getLocation();
    },
 
    //使用getDelta发现物体移动的没有手指移动的快。使用getUIDelta正常。
    onTouchMove(event) {
        console.info("onMove");
         // 计算移动的偏移量
        let delta = event.getUIDelta();

        this.newX = this.e1.position.x + delta.x;
        this.newY = this.e1.position.y +delta.y;

        
        // 更新节点位置
        this.e1.setPosition(this.newX,this.newY)
    },
 
    onTouchEnd(event) {
        // 触摸结束时可以处理一些事情
    },
 
    onDestroy() {
        // 清理注册的事件
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }
});

重点:要使用getUIDelta !!!

getDelta和getUIDelta有什么区别呢?全局与节点触摸和鼠标事件 API | Cocos Creator

这解释太拗口了,我是没读明白。

getDelta     获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。

getUIDelta  获取当前触点距离上一次触点移动在 UI 窗口内相对于左下角的距离对象,对象包含 x 和 y 属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值