一, RectTransformUtility.ScreenPointToLocalPointInRectangle

           Ⅰ, 将屏幕坐标转换成相对坐标. 猜想至少有2个重要参数: ①, 相对于哪一个GO的相对坐标 . ②, 屏幕坐标

           Ⅱ, Scene布置

Unity3D之ScreenPointToLocalPointInRectangle_RectTransformUtility

         Ⅲ, 脚本

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()
    {

    }
}

             解析代码参数

Unity3D之ScreenPointToLocalPointInRectangle_Unity3D_02

                    参数1,(canvas.transform as RectTransform): 得到相对于参数1(GO)上坐标

                    参数2( 注意: canvas 的render mode为: Screen Space -Overlay , 所以Image的世界坐标就是屏幕坐标): 得到Image屏幕坐标在参数1上的相对位置

            结果如下:

Unity3D之ScreenPointToLocalPointInRectangle_RectTransformUtility_03

 

二, 扩展

         Ⅰ, 将Image移动到鼠标点击的位置

         Ⅱ, 脚本如下

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都行