58 lines
2.1 KiB
TypeScript
58 lines
2.1 KiB
TypeScript
const { ccclass, property } = cc._decorator;
|
|
|
|
/** 物品拖動 */
|
|
@ccclass
|
|
export default class DragItem extends cc.Component {
|
|
//#region Lifecycle
|
|
|
|
protected onLoad(): void {
|
|
// 獲取小節點
|
|
let carNode: cc.Node = this.node;
|
|
// 新增變數判斷使用者當前滑鼠是不是處於按下狀態
|
|
let mouseDown: boolean = false;
|
|
// 當使用者點選的時候記錄滑鼠點選狀態
|
|
carNode.on(cc.Node.EventType.MOUSE_DOWN, (event) => {
|
|
mouseDown = true;
|
|
});
|
|
// 只有當使用者滑鼠按下才能拖拽
|
|
carNode.on(cc.Node.EventType.MOUSE_MOVE, (event) => {
|
|
if (!mouseDown) { return; }
|
|
// 獲取滑鼠距離上一次點的資訊
|
|
let delta: any = event.getDelta();
|
|
let canvasNode: cc.Node = cc.Canvas.instance.node;
|
|
// 增加限定條件
|
|
let minX: number = -canvasNode.width / 2 + carNode.width / 2;
|
|
let maxX: number = canvasNode.width / 2 - carNode.width / 2;
|
|
let minY: number = -canvasNode.height / 2 + carNode.height / 2;
|
|
let maxY: number = canvasNode.height / 2 - carNode.height / 2;
|
|
let moveX: number = carNode.x + delta.x;
|
|
let moveY: number = carNode.y + delta.y;
|
|
// 控制移動範圍
|
|
if (moveX < minX) {
|
|
moveX = minX;
|
|
} else if (moveX > maxX) {
|
|
moveX = maxX;
|
|
}
|
|
if (moveY < minY) {
|
|
moveY = minY;
|
|
} else if (moveY > maxY) {
|
|
moveY = maxY;
|
|
}
|
|
// 移動小車節點
|
|
carNode.x = moveX;
|
|
carNode.y = moveY;
|
|
});
|
|
// 當滑鼠抬起的時候恢復狀態
|
|
carNode.on(cc.Node.EventType.MOUSE_UP, (event) => {
|
|
mouseDown = false;
|
|
});
|
|
carNode.on(cc.Node.EventType.TOUCH_END, (event) => {
|
|
mouseDown = false;
|
|
});
|
|
carNode.on(cc.Node.EventType.TOUCH_CANCEL, (event) => {
|
|
mouseDown = false;
|
|
});
|
|
}
|
|
|
|
//#endregion
|
|
} |