using UnityEngine; public class ScreenToUI : MonoBehaviour { public const float UI_Width = 1366f; public const float UI_Height = 768f; public readonly static float Screen_Width_Half = Screen.width / 2f; public readonly static float Screen_Height_Half = Screen.height / 2f; public readonly static float Screen_UI_Ratio = UI_Width / UI_Height; public readonly static float Screen_Screen_Ratio = Screen.width / Screen.height; public readonly static float Screen_Width_Ratio = UI_Width / Screen.width; public readonly static float Screen_Height_Ratio = UI_Height / Screen.height; private Vector3 m_position_offset; private void Awake() { m_position_offset = Vector3.zero; //計算目標偏移量,遍歷到以中心爲錨點的父物體爲止 Transform target = transform; int index = 0, count = 0; while (target != null) { if (index++ < count) { m_position_offset += target.localPosition; target = target.parent; } else { break; } } } private void Update() { if (Input.GetMouseButton(0)) { Vector3 position = FormatPosition(Input.mousePosition); //do something... Debug.LogError(position); } } private Vector3 FormatPosition(Vector3 position) { float ratio_width = 1, ratio_height = 1; if (Screen_UI_Ratio != Screen_Screen_Ratio) { if (Screen_UI_Ratio < Screen_Screen_Ratio) { float real = Screen.height * Screen_UI_Ratio; ratio_width = Screen.width / real; } else { float real = Screen.width / Screen_UI_Ratio; ratio_height = Screen.height / real; } } position.x -= Screen_Width_Half; position.y -= Screen_Height_Half; position.x *= Screen_Width_Ratio * ratio_width; position.y *= Screen_Height_Ratio * ratio_height; position -= m_position_offset; return position; } }
屏幕座標以左下角爲座標ide
UGUI以中心爲座標spa
首先將座標位置轉換code
而後經過屏幕寬高比與UGUI設置的寬高比進行計算,UGUI.UIScaleMode = Scale With Screen Sizeorm
最後計算父物體與中心點的偏移量blog