当我自由移动相机时,我试图在Unity UI中的多维数据集上显示文本。画布设置为屏幕空间 - 摄像机模式,我在检查器中设置摄像机属性。我还将鼠标移动脚本附加到相机上。
我的问题是文本几乎没有移动,似乎忽略了立方体相对于相机视口的位置。这是我的代码:
public class UpdateUiMarker : MonoBehaviour {
public RectTransform element;
public Transform cube;
public RectTransform canvas;
// Update is called once per frame
void LateUpdate () {
Vector2 screenPos = Camera.main.WorldToScreenPoint(cube.position);
Vector2 localPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, screenPos, Camera.main, out localPos);
element.localPosition = localPos;
}
}
答案 0 :(得分:1)
首先,您可以使用world
相机查看填充为3D对象的cube
,然后其他相机ui
在剔除3D对象时查看您的UI元素。最后,canvas
Canvas放置您的UI元素。
然后,您可以这样编写代码:
var screen = world.WorldToScreenPoint(cube.transform.position);
screen.z = (canvas.transform.position - ui.transform.position).magnitude;
var position = ui.ScreenToWorldPoint(screen);
element.position = position; // element is the Text show in the UI.
答案 1 :(得分:0)
void LateUpdate () {
element.anchoredPosition = Input.mousePosition;
}
将元素的锚点设置为Vector2.zero的min和max。
答案 2 :(得分:0)
URP 的工作解决方案(也适用于延迟):
public static Vector2 WorldPositionToScreenSpaceCameraPosition(Camera worldCamera, Canvas canvas, Vector3 position)
{
Vector2 viewport = worldCamera.WorldToViewportPoint(position);
Ray canvasRay = canvas.worldCamera.ViewportPointToRay(viewport);
return canvasRay.GetPoint(canvas.planeDistance);
}