1、经测试发现UI的rectTransform坐标信息是以像素为单位,和ScreenPoint的单位是一致的,而ScreenPoint是以左下角为原点的二维坐标轴计算的,所以只要把UI的锚点设置为左下角,那么UI的rectTransform坐标位置就是ScreenPoint的位置。
ScreenPoint直接用unity的api:Camera.main.WorldToScreenPoint(worldPos)得到。
2、用以下办法能得到ui的世界坐标
private Transform target;
private RectTransform rectTransform;
private void Awake() {
rectTransform = GetComponent<RectTransform>();
}
private void Update() {
if (rectTransform == null || target == null)
return;
// 得到屏幕坐标
Vector2 screenPos = Camera.main.WorldToScreenPoint(target.position);
// 通过自身的rectTransform、屏幕坐标、和ui摄像机获得世界坐标
Vector3 worldPos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform,screenPos,UI_Camera.Instance.Camera,out worldPos)) {
transform.position = worldPos;
}
}
本文介绍如何在Unity中将UI元素的坐标从屏幕坐标转换到世界坐标,并解释了UI的rectTransform坐标信息是以像素为单位,与ScreenPoint一致。通过具体的C#代码示例,展示了如何获取UI元素的世界坐标。
1万+

被折叠的 条评论
为什么被折叠?



