点座標のスクリーン座標をオンUGUI画面適応を[含みます]

使用してUnityEngineを。

パブリック クラスScreenToUI:MonoBehaviour 
{ 
    公共 のconst  フロート UI_Width = 1366f。
    公共 のconst  フロート UI_Height = 768f; 

    公共の 読み取り専用 静的な フロート Screen_Width_Half = Screen.width / 2F。
    公共の 読み取り専用 静的な フロート Screen_Height_Half = Screen.height / 2F。

    公共の 読み取り専用 静的な フロート Screen_UI_Ratio = UI_Width / UI_Height。
    公共の 読み取り専用 静的な フロート= Screen.width Screen_Screen_Ratio / screen.height; 

    パブリック 読み取り専用の 静的 フロート Screen_Width_Ratio = UI_Width / screen.widthと、
     パブリック 読み取り専用の 静的 フロート Screen_Height_Ratio = UI_Height / screen.heightと、

    プライベートするVector3 m_position_offset、

    プライベート ボイドアウェイク()
    { 
        m_position_offset = Vector3.zero。

        //は、親オブジェクトアンカーまで中心に横断するように、目標シフト量を算出する 
        変換=ターゲット変換; 

        int型のインデックス= 0、COUNT = 0 ; 

        一方(!=ターゲットヌルを
        { 
            場合(インデックスは++ < カウント数)
            { 
                m_position_offset + = target.localPosition。

                ターゲット = target.parent。
            } 
            
            { 
                破ります
            } 
        } 
    } 

    プライベート ボイド更新()
    { 
        場合(Input.GetMouseButton(0 ))
        { 
            するVector3位置 = FormatPosition(Input.mousePosition)。

            // 何かを...

            Debug.LogError(位置)。
        } 
    } 

    プライベートのVector3 FormatPosition(するVector3位置)
    { 
        フロート ratio_width = 1、ratio_height = 1 

        もし(Screen_UI_Ratio =!Screen_Screen_Ratio)
        { 
            場合(Screen_UI_Ratio < Screen_Screen_Ratio)
            { 
                float型リアル= Screen.height * Screen_UI_Ratioを。
                ratio_width = Screen.width / 本物。
            } 
            
            { 
                フロート実= Screen.width /  Screen_UI_Ratioと、
                ratio_heightを = Screen.height / 本物。
            } 
        } 

        position.x - = Screen_Width_Half。
        position.y - = Screen_Height_Half。

        position.x * = Screen_Width_Ratio *のratio_width。
        position.y * = Screen_Height_Ratio *のratio_height。

        位置 - = m_position_offset。

        戻り値の位置; 
    } 
}
コードの表示

 

画面左下隅の座標に座標

UGUI中心座標

最初の位置を座標変換します

次に、アスペクト比は、画面サイズのアスペクト比とUGUI、UGUI.UIScaleMode =スケールを設定することによって計算されます

最後に、親オブジェクトと中心点のオフセットを算出します

 

おすすめ

転載: www.cnblogs.com/Joke-crazy/p/11696548.html