我们要实现的效果是,按住并拖动一个小物体,物体跟随手指(鼠标)移动。
代码DragToAnywhere.ts
const { ccclass,property } = cc._decorator;
@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);
this.node.off(cc.Node.EventType.TOUCH_END,this);
}
// update (dt) {}
_onTouchMove(touchEvent) {
let location = touchEvent.getLocation();
this.node.position = this.node.parent.convertToNodeSpaceAR(location); // 确定位置
}
_onTouchEnd(touchEvent) {
// 放下
}
}
把DragToAnywhere.ts挂在预制体上。在场景中创建预制体对象。
let node1 = cc.instantiate(this.drag_item);
this.node.addChild(node1);
node1.x = 100;
node1.y = 100;
node1.getComponent(DragToAnywhere).label.string = '水星';
工程请查看github/CCCTry
参考:
Cocos Creator: https://rustfisher.com/categories/CocosCreator/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。