鼠标移动3D物体,怎么能让物体一直跟着鼠标呢? 我这里实现的移动会产生偏差

红色是鼠标位置,移动过程中和移动的小球有距离,有没有好的办法处理一下呢。

const _tempOut = new Vec3();

@ccclass('test')
export class test extends Component {
    @property(CameraComponent)
    public camera: CameraComponent = null;

    @property(Node)
    public model: Node = null;

    // canvas
    @property(Node)
    public root: Node = null;

    private _pos = new Vec3();

    public start () {
        systemEvent.on(SystemEventType.TOUCH_START, this.touchStart, this);
    }

    public touchStart(touch: Touch, event: EventTouch) {
        const screenPos = touch.getLocation();
        const uiPos = touch.getUILocation();
        this._pos.set(uiPos.x, uiPos.y, 0);
        const uitransform = this.root.getComponent(UITransformComponent);
        // 将触摸到的 ui 世界坐标转换到相对 canvas 下的本地坐标
        uitransform.convertToNodeSpaceAR(this._pos, _tempOut);
        // ui 同步
        this.node.setPosition(_tempOut);
        // 这里的 z = 0.005 代表相机的 farClip 和 nearClip 之间的差值,范围是 [0,1],也决定了你转换后的坐标距离相机的一个深度
        this._pos.set(screenPos.x, screenPos.y, 0.005);
        this.camera.screenToWorld(this._pos, _tempOut);
        // 模型同步
        this.model.setWorldPosition(_tempOut);
    }
}

看看这个对你有帮助吗

2赞

哇,放空小姐姐~ 我刚刚终于解决了这个问题~ 用射线和平面交点做成了~ 谢谢你 嘻嘻

解决方案参考:

1赞