cocos creator3.7版本拖拽事件处理

前言:网上能找到的资料都太落后了,导致哥们用AI去写,全是瞎B写,版本都不对。贴点实际有用的。别老捣鼓你那破convertToNodeSpaceAR或者convertToNodeSpace了。

核心代码

touch.getDeltaX()
touch.getDeltaY()
在这里插入图片描述

在cocoscreator3.7版本中通过这个方法,修改节点坐标就可以了。

import { _decorator, Button, Component, EventTouch, Node, systemEvent, UITransform, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('LockManager')
export class LockManager extends Component {
    @property(Node)
    public dragNode: Node = null; // 假设这是您想要拖拽的 Sprite 所在的节点

    @property(Node)
    public transformNode: Node = null; // 假设这是您想要移动的node节点

    private _isDragging = false;

    start() {
        if (this.dragNode) {
            this.dragNode.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
            this.dragNode.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
            this.dragNode.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
            this.dragNode.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
        }
    }

    onTouchStart(touch: EventTouch) {
        this._isDragging = true;
    }

    onTouchMove(touch: EventTouch) {
        if (!this._isDragging) return;
        // 更新节点的y坐标
        const originPos = this.transformNode.getPosition()
        originPos.y += touch.getDeltaY();
        this.transformNode.setPosition(originPos)
    }

    onTouchEnd(touch: EventTouch) {
        this._isDragging = false;
        // 可以在这里添加拖拽结束后的逻辑
    }

    onTouchCancel(touch: EventTouch) {
        this._isDragging = false;
        // 可以在这里添加触摸被取消的逻辑
    }

    onDestroy() {
        if (this.dragNode) {
            this.dragNode.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
            this.dragNode.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
            this.dragNode.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
            this.dragNode.off(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值