用ts语言写一个cocos creator中拖拽物体的代码
以下是使用 TypeScript 语言编写的 Cocos Creator 中拖拽物体的代码:
-
首先,需要在场景中创建一个节点,并将其添加到 Canvas 节点下。创建一个脚本组件,命名为 DragObject。
-
在 DragObject 组件中,先定义需要使用的变量:
const {ccclass, property} = cc._decorator;
@ccclass
export default class DragObject extends cc.Component {
// 需要拖拽的节点
@property(cc.Node)
dragNode: cc.Node = null;
// 是否可以拖拽
@property()
canDrag: boolean = true;
// 是否限制在父节点范围内
@property()
limitParent: boolean = false;
// 父节点
private parent: cc.Node = null;
// 偏移量
private offset: cc.Vec2 = cc.v2(0, 0);
}
- 在 onLoad 生命周期回调函数中,初始化变量:
onLoad () {
// 获取父节点
this.parent = this.node.parent;
// 绑定事件
this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
}
- 实现触摸事件回调函数:
private onTouchStart (event: cc.Touch) {
if (!this.canDrag) return;
// 计算偏移量
const worldPos = this.node.convertToWorldSpaceAR(this.dragNode.position);
const localPos = this.parent.convertToNodeSpaceAR(worldPos);
this.offset = localPos.sub(event.getLocation());
// 改变节点的层级顺序,使其置于最上层
this.node.setSiblingIndex(this.parent.childrenCount - 1);
}
private onTouchMove (event: cc.Touch) {
if (!this.canDrag) return;
// 计算新的位置
const pos = event.getLocation().add(this.offset);
// 限制位置在父节点范围内
if (this.limitParent) {
const minX = -this.parent.width / 2 + this.dragNode.width / 2;
const maxX = this.parent.width / 2 - this.dragNode.width / 2;
const minY = -this.parent.height / 2 + this.dragNode.height / 2;
const maxY = this.parent.height / 2 - this.dragNode.height / 2;
pos.x = cc.misc.clamp(pos.x, minX, maxX);
pos.y = cc.misc.clamp(pos.y, minY, maxY);
}
// 更新节点位置
this.dragNode.position = this.parent.convertToNodeSpaceAR(pos);
}
private onTouchEnd (event: cc.Touch) {
// do something
}
private onTouchCancel (event: cc.Touch) {
// do something
}
- 最后,在脚本组件上挂载需要拖拽的节点,并设置相应的属性即可。
@property(cc.Node)
dragNode: cc.Node = null;
@property()
canDrag: boolean = true;
@property()
limitParent: boolean = false;
以上就是使用 TypeScript 语言编写的 Cocos Creator 中拖拽物体的代码。
原文地址: https://www.cveoy.top/t/topic/yzW 著作权归作者所有。请勿转载和采集!