屏幕坐标(Input.mousePosition)转换UI坐标

屏幕坐标(Input.mousePosition)转换UI坐标

需要了解到的知识点

1:屏幕坐标的起点位置 左下角为(0,0)点,右上角为(Screen.width,Screen.height)

2:UI坐标的起点位置 屏幕中心点

方法1
            Vector2 uisize = canvas.GetComponent<RectTransform>().sizeDelta;//得到画布的尺寸
            Vector2 screenpos = Input.mousePosition;
            Vector2 screenpos2;
            screenpos2.x = screenpos.x - (Screen.width / 2);//转换为以屏幕中心为原点的屏幕坐标
            screenpos2.y = screenpos.y - (Screen.height / 2);
            Vector2 uipos;//UI坐标
            uipos.x = screenpos2.x*  (uisize.x / Screen.width);//转换后的屏幕坐标*画布与屏幕宽高比
            uipos.y = screenpos2.y * ( uisize.y / Screen.height);
方法2
            Vector3 worldPos=Camera.main.ScreenToWorldPoint(Input.mousePosition);//屏幕坐标转换世界坐标
            Vector2 uiPos = canvas.transform.InverseTransformPoint(worldPos);//世界坐标转换位本地坐标
方法3
Vector2 uipos = Vector3.one;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,
            Input.mousePosition, Camera.main, out uipos);
//将屏幕空间点转换为RectTransform的局部空间中位于其矩形平面上的位置。
//cam参数是与屏幕点关联的摄像机。对于Canvas中设置为Screen Space - Overlay模式的RectTransform,cam参数应为null。
//当在提供PointerEventData对象的事件处理程序中使用ScreenPointToLocalPointInRectangle时,可以使用PointerEventData.enterEventData(用于悬停功能)或PointerEventData.pressEventCamera(用于单击功能)获取正确的摄像头。这将自动为给定事件使用正确的相机(或null)。

转载于:https://www.cnblogs.com/grassgarden/p/9782650.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值