39 lines
1.5 KiB
TypeScript
39 lines
1.5 KiB
TypeScript
|
import { _decorator, Component, Node,clamp, EventTouch, Vec2, Rect, misc } from 'cc';
|
||
|
const { ccclass, property } = _decorator;
|
||
|
|
||
|
@ccclass('BackgroundDrag')
|
||
|
export class BackgroundDrag extends Component {
|
||
|
private startTouchPos: Vec2 = new Vec2(0, 0); // 记录初始触摸位置
|
||
|
private startNodePos: Vec2 = new Vec2(0, 0); // 记录初始节点位置
|
||
|
|
||
|
@property(Node)
|
||
|
public backgroundNode: Node = null; // 拖动的背景节点
|
||
|
|
||
|
// 限制背景移动的范围
|
||
|
@property(Rect)
|
||
|
public movementBounds: Rect = new Rect(0, 0, 1000, 1000);
|
||
|
|
||
|
onLoad() {
|
||
|
this.backgroundNode.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
|
||
|
this.backgroundNode.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
|
||
|
}
|
||
|
|
||
|
onTouchStart(event: EventTouch) {
|
||
|
this.startTouchPos = event.getLocation(); // 获取触摸起始点
|
||
|
this.startNodePos = new Vec2(this.backgroundNode.position.x, this.backgroundNode.position.y); // 记录背景节点的起始位置
|
||
|
}
|
||
|
|
||
|
onTouchMove(event: EventTouch) {
|
||
|
const touchPos = event.getLocation();
|
||
|
const delta = touchPos.subtract(this.startTouchPos);
|
||
|
|
||
|
let newPos = this.startNodePos.add(delta);
|
||
|
|
||
|
// 限制新位置在给定的范围内
|
||
|
newPos.x = clamp(newPos.x, this.movementBounds.xMin, this.movementBounds.xMax);
|
||
|
newPos.y = clamp(newPos.y, this.movementBounds.yMin, this.movementBounds.yMax);
|
||
|
|
||
|
this.backgroundNode.setPosition(newPos.x, newPos.y, this.backgroundNode.position.z);
|
||
|
}
|
||
|
}
|