Unity各种坐标转换

屏幕坐标转换成世界坐标

   /// <summary>
    /// 屏幕坐标转换成世界坐标
    /// </summary>
    /// <param name="ScreenPoint">屏幕鼠标点击点</param>
    /// <param name="target">要转换的物体</param>
    /// <returns></returns>
    Vector3 MyScreenPointToWorldPoint(Vector3 ScreenPoint, Transform target)
    {
        //1 得到物体在主相机的xx方向
        Vector3 dir = (target.position - Camera.main.transform.position);
        //2 计算投影 (计算单位向量上的法向量)
        Vector3 norVec = Vector3.Project(dir, Camera.main.transform.forward);
        //返回世界空间
        return Camera.main.ViewportToWorldPoint
            (
               new Vector3(
                   ScreenPoint.x / Screen.width,
                   ScreenPoint.y / Screen.height,
                   norVec.magnitude
               )
            );
    }

根据世界坐标得到相对于某个UI Canvas的坐标

 /// <summary>
        /// 根据世界坐标得到相对于某个UI Canvas的坐标
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="canvas"></param>
        /// <returns></returns>
        public Vector2 GetTargetPoint(GameObject obj, Canvas canvas = null)
        {
            Vector3 pos = obj.transform.localPosition;
            UnitBase unitb = obj.GetComponent<UnitBase>();
            //if (unitb != null && unitb.UnitType == UnitEnum.Monster)
            //{
            //    //pos += Vector3.up * 0.5f;
            //}
            //else if (unitb != null && unitb.UnitType == UnitEnum.RepairTable)
            //{
            //    pos += Vector3.up * 0.5f;
            //}
            if (canvas == null)
                canvas = UIRoot;
            Vector2 Pos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, GlobalConfigComponent.Instance.CameraMain.WorldToScreenPoint(pos), canvas.worldCamera, out Pos);
            return Pos;
        }

屏幕坐标转换成某个UICanvas坐标
1.屏幕坐标转换成世界坐标
2.世界坐标转换成某个UICanvas坐标

/// <summary>
        /// 屏幕坐标转换成某个UICanvas坐标
        /// </summary>
        /// <param name="pos">屏幕坐标</param>
        /// <param name="canvas">UICanvas</param>
        /// <returns></returns>
        public Vector2 GetTargetPoint(Vector3 pos, Canvas canvas = null)
        {
            pos = Camera.main.ScreenToWorldPoint(pos);//从屏幕空间转换到世界空间
            if (canvas == null)
                canvas = UIRoot;
            Vector2 Pos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, GlobalConfigComponent.Instance.CameraMain.WorldToScreenPoint(pos), canvas.worldCamera, out Pos);
            return Pos;
        }

自我总结:
得到UI上物品的3D相机左边:
首先根据UI相机把坐标转成屏幕坐标,然后再根据3D相机把屏幕坐标转成世界坐标

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值