Screen coordinates (input.mouseposition) convert UI coordinates

Source: Internet
Author: User

Screen coordinates (input.mouseposition) the knowledge points that need to be learned to translate UI coordinates

1: The bottom left corner of the screen coordinates is (0,0), the upper-right corner is (screen.width,screen.height)

2:ui coordinates the start position of the screen center point

Method 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);
Method 2
            Vector3 worldPos=Camera.main.ScreenToWorldPoint(Input.mousePosition);//屏幕坐标转换世界坐标            Vector2 uiPos = canvas.transform.InverseTransformPoint(worldPos);//世界坐标转换位本地坐标
Method 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)。

Screen coordinates (input.mouseposition) convert UI coordinates

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.