我們要實現的效果是,按住並拖動一個小物體,物體跟隨手指(鼠標)移動。
拖到指定位置放下。如果沒有到指定位置,則回到上一個位置。
新建腳本DragToTarget.ts,掛到預制體上。
const { ccclass, property } = cc._decorator;
@ccclass
export default class DragToTarget extends cc.Component {
@property(cc.Label)
nameLabel: cc.Label = null;
@property(cc.Node)
targetOfDragList: cc.Node[] = [];
_oldPos = null; // 上一個位置
start() {
this._oldPos = this.node.position;
}
onEnable() {
this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
}
onDisable() {
this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
}
// update (dt) {}
_onTouchMove(touchEvent) {
let location = touchEvent.getLocation();
this.node.position = this.node.parent.convertToNodeSpaceAR(location); // 確定位置
}
_onTouchEnd(touchEvent) {
if (this.targetOfDragList.length === 0) {
return; // 沒有目標位置
}
let inTarget = false;
for (const targetNode of this.targetOfDragList) {
if (this._withinTarget(targetNode, touchEvent)) {
inTarget = true;
break;
}
}
if (!inTarget) {
this.node.position = this._oldPos; // 回去
}
}
// 判斷觸摸事件是否在槽位里
_withinTarget(targetNode: cc.Node, touchEvent) {
let rect = targetNode.getBoundingBox();
let location = touchEvent.getLocation();
let point = targetNode.parent.convertToNodeSpaceAR(location);
return rect.contains(point);
}
}
思路與之前的拖動類似。
在最后TOUCH_END
的時候,判斷自己是否在目標區域內。
如果不在則返回上一個坐標。
在場景中使用
import DragToTarget from "./DragToTarget";
const { ccclass, property } = cc._decorator;
@ccclass
export default class DragToControl extends cc.Component {
@property(cc.Prefab)
drag_to_item: cc.Prefab = null;
@property(cc.Node)
dragTargets: cc.Node[] = [];
itemNum = 1;
start() {
this.createItem();
}
// update (dt) {}
createItem() {
let d = cc.instantiate(this.drag_to_item);
this.node.addChild(d);
let dragTo = d.getComponent(DragToTarget);
dragTo.targetOfDragList = this.dragTargets; // 設置目的地
dragTo.nameLabel.string = '' + this.itemNum++;
}
}
參考:
Cocos Creator: https://rustfisher.com/categories/CocosCreator/