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)
Camera camera = GameObject.Find("Main Camera").GetComponent<Camera>();
Vector3 screenPos = camera .WorldToScreenPoint(transform.postion)
浙公网安备 33010602011771号