UGUI获取UI的2D坐标

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class GetMousePos : MonoBehaviour
{
    public Canvas canvas;//画布
    public RectTransform rectTsf;

    void Start()
    {
        canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 pos;
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out pos))
{
rectTsf.anchoredPosition
= pos;
Debug.Log(pos);
}
}
}
}

 

 如果是UI组件,先把世界坐标转换成屏幕坐标,替换掉Input.mousePosition即可

Camera camera = GameObject.Find("Main Camera").GetComponent<Camera>();

Vector3 screenPos = camera .WorldToScreenPoint(transform.postion) 

posted on 2017-10-24 11:08  Vicky_Liu  阅读(377)  评论(0)    收藏  举报

导航