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

  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);
            }
        }
    }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值