我们要实现的效果是,按住并拖动一个小物体,物体跟随手指(鼠标)移动。

代码DragToAnywhere.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@ccclass
export default class DragToAnywhere extends cc.Component {

@property(cc.Label)
label: cc.Label = null;

start () {

}

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) {
// 放下
}
}

DragToAnywhere.ts挂在预制体上。在场景中创建预制体对象。

1
2
3
4
5
let node1 = cc.instantiate(this.drag_item);
this.node.addChild(node1);
node1.x = 100;
node1.y = 100;
node1.getComponent(DragToAnywhere).label.string = '水星';