根据触摸位置设置节点位置,位置计算感觉有些问题

@ccclass('Test')
export class Test extends Component {
   //触摸ID
   private touchID: number;
   private moveForce: Vec2 = new Vec2();
   private uiTransform: UITransform;
   private touchLocation: Vec2;
   private currentPosition: Vec3;

   start() {
       this.uiTransform = this.node.getComponent(UITransform);
       this.node.on(NodeEventType.TOUCH_START, this.touchStart, this);
       this.node.on(NodeEventType.TOUCH_MOVE, this.touchMove, this);
       this.node.on(NodeEventType.TOUCH_END, this.touchEnd, this);
       this.node.on(NodeEventType.TOUCH_CANCEL, this.touchEnd, this);
   }

   update(deltaTime: number) {

   }

   private touchStart(e: EventTouch) {
       this.touchID = e.getID();
       let touchPosition = e.getLocation(this.touchLocation);
       let convertPosition =
           this.uiTransform.convertToNodeSpaceAR(new Vec3(touchPosition.x, touchPosition.y, 0), this.currentPosition);
       this.node.position = convertPosition;
   }

   private touchMove(e: EventTouch) {
       if (this.touchID != e.getID()) {
           return;
       }
       let touchPosition = e.getLocation(this.touchLocation);
       console.log("touchPosition" + touchPosition)
       let convertPosition =
           this.uiTransform.convertToNodeSpaceAR(new Vec3(touchPosition.x, touchPosition.y, 0), this.currentPosition);
       console.log("convertPosition" + convertPosition);
       this.moveForce = new Vec2(convertPosition.x, convertPosition.y).normalize();
       this.node.position = convertPosition;
   }

   private touchEnd(e: EventTouch) {
       if (this.touchID != e.getID()) {
           return;
       }
       this.moveForce = v2();
       this.node.position = new Vec3();
   }
}

脚本如上,期望实现节点跟随触摸点,但是实现出来节点一直在闪烁。根据log感觉同样的参数计算结果并不一致。这是什么原因呢?有大佬解答吗?

是3.7.0版本吗,3.6有这个问题吗?

可能你需要的是 e.getUILocation

像这样?

这是项目源代码:li231904.zip (1.2 MB)

1赞

有,3.6子版本都这样。

试了,不行。根据log看传进入同样的参数获得了不同的结果

this.uiTransform 取的应该是 this.node 的父节点的,还有要使用 getUILocation

完全跟随 :rofl:

我也是。。。各种试都不行