第一种方式:
onElMove(event:EventTouch){
console.info("onMove");
this.e1.setWorldPosition(event.getUILocation().x,event.getUILocation().y,0);
}
这种方式有缺陷,因为当手指落下时,点击的位置不是Node的中心位置时,移动前会出现一个跳跃的行为,这种使得操作不连贯,效果很不好。
第二种方式: 通过偏移量(getUIDelta)来决定Node的位置,这种才是最好的方式 。
cc.Class({
extends: cc.Component,
start() {
// 获取DragonBones实例
this.dragonBonesNode = this.getComponent(cc.DragonBonesComponent);
// 获取节点的collider组件
this.collider = this.node.getComponent(cc.Collider);
// 如果没有collider组件,则添加一个box collider
if (!this.collider) {
this.collider = this.node.addComponent(cc.BoxCollider);
}
// 注册触摸事件
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);
},
onTouchStart(event) {
// 记录开始触摸的位置
this.startPos = event.getLocation();
},
//使用getDelta发现物体移动的没有手指移动的快。使用getUIDelta正常。
onTouchMove(event) {
console.info("onMove");
// 计算移动的偏移量
let delta = event.getUIDelta();
this.newX = this.e1.position.x + delta.x;
this.newY = this.e1.position.y +delta.y;
// 更新节点位置
this.e1.setPosition(this.newX,this.newY)
},
onTouchEnd(event) {
// 触摸结束时可以处理一些事情
},
onDestroy() {
// 清理注册的事件
this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
}
});
重点:要使用getUIDelta !!!
getDelta和getUIDelta有什么区别呢?全局与节点触摸和鼠标事件 API | Cocos Creator
这解释太拗口了,我是没读明白。
getDelta 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。
getUIDelta 获取当前触点距离上一次触点移动在 UI 窗口内相对于左下角的距离对象,对象包含 x 和 y 属性。