射线检测点击屏幕的点,换成一个准心图标,射线位置有偏移。

参考射线检测的demo,将射线检测中,用点击屏幕的获取射线目标点,换成一个准心图标,检测结果位置有偏移。屏幕中间的准心点,需要做怎样的转换啊。

demo中,this.ami 是加在屏幕中的准心,做以下修改:

this.cameraCom.screenPointToRay(touch._point.x, touch._point.y, this._ray);

this.cameraCom.screenPointToRay(this.ami.node.worldPosition.x,this.ami.node.worldPosition.y, this._ray);

screenPoint 要的是一个屏幕空间的点,this.ami.node.worldPosition 是世界空间的

通过node,怎么获得这个点啊

不是很明白你这里确切要的是怎样的

如果是屏幕点的话通过:touch.getLocation() 获取屏幕点(屏幕点不是 UI 坐标点,其间存在屏幕适配问题)

如果要转换到 UI 坐标下的话,可以通过 :touch.getUILocation() 获取点击点,再转换到 UI 某个节点的本地坐标的话,可以通过:uitransform.convertToNodeSpaceAR

节点的世界坐标:this.node.worldPosition

3D 节点转换到 UI 节点:camera.convertToUINode

1赞

将UI点,转化为屏幕点呢?

通过UI上sprite的坐标点,作为this.cameraCom.screenPointToRay发射的目标点。

也就是将this.aim这个sprite的坐标怎么转换后,用于this.cameraCom.screenPointToRay的屏幕点的入参。

你这里的出发点不应该是 ui 转屏幕,而是屏幕点控制 ui 图标位置和射线的发射点

摇杆控制摄像机移动,射线点在屏幕中间,在onTouchMove中调用射线检测。

//获取频幕中心点
this.screenPoint = new Vec2(view.getFrameSize().width,view.getFrameSize().height);

//赋UI Sprite坐标
this.ami.node.worldPosition = new Vec3(this.screenPoint.x,this.screenPoint.y,0);

//发射射线
this.cameraMain.screenPointToRay(this.screenPoint.x, this.screenPoint.y, this.ray);

是这样子的吗,检测的用效区明显不对。

如何获得屏幕中心点,用于射线检测啊?各种测试都不对。

搞了好几天了,请回复哈

        /**
         * 注意一点,目前相机的初始化在 start 之后才完成,所以暂时别在start里面变换坐标
         */

        /**
         * 首先获取到此挂载此ui的 canvas, 将此节点的世界坐标转换到 canvas 相机下的屏幕坐标
         */
        const canvas = this.node.parent.getComponent(CanvasComponent); // 这里改成你项目的canvas
        const screenP = new Vec3();
        canvas.camera.worldToScreen(screenP, this.node.worldPosition)

        /**
         * 再根据屏幕坐标和 3d 相机,获得从3d相机射出的世界射线
         */
        const ray = new geometry.ray();
        const d3camera = this.node.parent.parent.children[2].getComponent(CameraComponent); // 这里改成你项目的3d相机
        d3camera.screenPointToRay(screenP.x, screenP.y, ray);

        // 最后就是做检测了,往接口填参数,这里以检测物理碰撞盒为例子
        if (PhysicsSystem.instance.raycast(ray)) {
            const r = PhysicsSystem.instance.raycastResults;
            /** TODO */
        }
1赞

屏幕中心用 view 的 getCanvasSize 取宽高一半,ui 中心用 getVisibleSize 取宽高一半

这个管用。谢谢!

this.node.worldPosition
查不到 woldPosition啊

https://docs.cocos.com/creator3d/api/zh/classes/scene_graph.node.html#worldposition

6666 牛逼 刚好碰到这个需求 ui直接跟3d相机转换会有偏差 ,ui转canvas下后,完美解决

3赞