Unity UI显示3D模型,控件与屏幕分辨率不同,导致在屏幕上鼠标点选模型,无法选中模型的问题

​UI界面显示3d模型,需要添加模型相机,通过中间RenderTexture来连接相机与界面的承载容器【RawImage】,根据项目在显示时,会对界面做适当调整,但是RawImage的宽和高会产生运行时,鼠标点击屏幕坐标,获取模型碰撞体的问题,因为RawImage和当前屏幕分辨率的不匹配,导致鼠标点击屏幕时的位置,相较于看到的点击选中发生偏移。

 public Camera modelCamera;
    RaycastHit hit;
    Ray ray;
    /// <summary>
    /// 图层索引
    /// </summary>
    int layerIndex = 0;
    //3d渲染在2d界面显示的内容
    public RawImage rawImage;
    //图片和屏幕的宽和高
    public float imageWidth = 0;
    public float imageHeight = 0;
    public float screenWith = 0;
    public float screenHeight = 0;
    // Start is called before the first frame update
    void Start()
    {
        layerIndex = LayerMask.GetMask("model");
        screenWith = Screen.currentResolution.width;
        screenHeight = Screen.currentResolution.height;
        imageWidth = rawImage.rectTransform.rect.width;
        imageHeight = rawImage.rectTransform.rect.height;
    }
    // Update is called once per frame
    void Update()
    {
        Vector3 clickPosInRawImg = Input.mousePosition;
        if (Input.GetMouseButton(0))
        {     
            //(屏幕的宽度-承载图片的宽度)/2
            //计算屏幕与承载图片宽和高的差值
            float localDiffX = (screenWith - imageWidth) / 2.0f;
            //(屏幕的高度-承载图片的高度)/2
            float localDiffY = (screenHeight - imageHeight) / 2.0f;
            //获取鼠标偏移后的位置
            float xPoint = clickPosInRawImg.x - localDiffX;
            float yPint = clickPosInRawImg.y - localDiffY;
            //获取差集后的鼠标位置点,作为发射线的点
            ray = modelCamera.ScreenPointToRay(new Vector2(xPoint, yPint));
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerIndex))
            {
                Debug.DrawLine(ray.origin, hit.point, Color.red);
                Debug.Log(hit.collider.name);
            }
        }
    }

 

 

posted @ 2023-01-10 12:12  天翊无影  阅读(215)  评论(0编辑  收藏  举报