Sometimes some Tips interfaces in the game need to dynamically display the location of the Tips interface based on the clicked position.
This case is very useful.
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 测试根据鼠标点击的位置来转换成UI坐标
/// </summary>
public class PosTransPanel : MonoBehaviour
{
private Image _image = null;
private Camera _camera = null;
private Transform _canvasTrans = null;
void Start()
{
_image = transform.parent.Find("Image").GetComponent<Image>();
_camera = Camera.main;
_canvasTrans = transform.parent;
}
private void LateUpdate()
{
//鼠标左键点击
if (Input.GetKeyDown(KeyCode.Mouse0))
{
//获取鼠标点击的坐标
Vector3 screenPos = _camera.WorldToScreenPoint(Input.mousePosition);
//把屏幕坐标转换成UI坐标
_image.transform.localPosition = ScreenToUIPos(screenPos);
}
}
/// <summary>
/// 屏幕坐标转换成UI坐标
/// </summary>
/// <param name="spos">屏幕坐标</param>
/// <returns>UI坐标</returns>
public Vector2 ScreenToUIPos(Vector3 screenPos)
{
Vector2 localPos;
// 画布Canvas 屏幕坐标 相机 转换后的UI坐标
RectTransformUtility.ScreenPointToLocalPointInRectangle(_canvasTrans as RectTransform, screenPos, _camera, out localPos);
return localPos;
}
}