Unity3D之ScreenPointToLocalPointInRectangle

一, RectTransformUtility.ScreenPointToLocalPointInRectangle

           Ⅰ, 將屏幕座標轉換成相對座標. 猜測至少有2個重要參數: ①, 相對於哪個GO的相對座標 . ②, 屏幕座標canvas

           Ⅱ, Scene佈置ide

         Ⅲ, 腳本this

using UnityEngine;
using UnityEngine.UI;

public class UIScripts : MonoBehaviour
{
    [SerializeField]
    private Image image;
    public Canvas canvas;
    void Start()
    {
        Vector2 pos;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
            canvas.transform as RectTransform,
            this.image.transform.position,
            this.canvas.worldCamera,
            out pos))
        {
            Debug.Log(pos);
        }
        this.getImagePos();
    }


    private void getImagePos()
    {
        RectTransform rectT = this.image.transform as RectTransform;
        Debug.Log(" ------ " + rectT.anchoredPosition);
    }

    void Update()
    {

    }
}

             解析代碼參數spa

                    參數1,(canvas.transform as RectTransform): 獲得相對於參數1(GO)上座標code

                    參數2( 注意: canvas 的render mode爲: Screen Space -Overlay , 因此Image的世界座標就是屏幕座標): 獲得Image屏幕座標在參數1上的相對位置orm

            結果以下:blog

 

二, 擴展

         Ⅰ, 將Image移動到鼠標點擊的位置ip

         Ⅱ, 腳本以下get

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIClickScripts : MonoBehaviour
{
    [SerializeField]
    private Image image;
    public Canvas canvas;

    private Vector2 pos;
    void Start()
    {

    }
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
    this.canvas.transform as RectTransform,//Local Panel
    Input.mousePosition,//Screen Pos
    canvas.worldCamera,
    out this.pos
 ))
            {
                (this.image.transform as RectTransform).anchoredPosition = this.pos;
            }
        }

    }
}

         Ⅲ, 其實能夠作一個緩動用Tween 或者用Unity自動的Lerp都行it

相關文章
相關標籤/搜索