鼠标屏幕位置,ui屏幕位置,ui大小,摄像机从屏幕向空间发射射线检测物体

 

鼠标屏幕位置

 Vector2 moutPosition =  Input.mousePosition;

获得ui在屏幕中的位置

       中心点在中间是(0,0),向左是正,向右是负,上正下负

//img_Camera1 是UI

 if (RectTransformUtility.ScreenPointToLocalPointInRectangle( Canvas, Camera.main.WorldToScreenPoint(Img_Camera1.transform.position), Camera.main, out convertedPos))
        {
            Debug.Log("================ " + convertedPos);
        }

获得世界物体和本地物体的坐标转换

这里注意了,世界物体的坐标用的是主相机转换的,其他的不变

  • recttransform.archoredPosition是相对于锚点的位置,并不是屏幕位置
  • recttransform.localPosition也是相对位置,相对于父transform的位置
var camera = UsingUnityUtils.GetUICamera();
var screenpoint = mainCamera.WorldToScreenPoint(worldPos);

Vector2 position = Vector2.zero;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
rectTransformParent, screenpoint, camera, out position);

 

获得ui 大小

Debug.Log("ui的大小========== " + Img_Camera1.rectTransform.rect);

输出结果:ui的大小========== (x:-547.45, y:-990.24, width:1094.90, height:1980.47)

ui与锚点的距离

Debug.Log("ui相对锚点位置越近越小=========== " + Img_Camera1.rectTransform.sizeDelta);

摄像机向空间发射射线,检测空间中的物体,物体可以隐藏mesh,只用碰撞体

 if (Input.GetMouseButton(0))
        {
            //从摄像机发出到点击坐标的射线
            Ray ray = camera1.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                //划出射线,只有在scene视图中才能看到
                Debug.DrawLine(ray.origin, hitInfo.point);
                GameObject gameObj = hitInfo.collider.gameObject;
                Debug.Log("click object name is " + gameObj.name);
                //当射线碰撞目标为boot类型的物品,执行拾取操作
                if (gameObj.tag == "boot")
                {
                    Debug.Log("pickup!");
                }
            }
        }

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值