前言:网上能找到的资料都太落后了,导致哥们用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);
}
}
}