这个是最近工作当中遇到的问题,世界坐标转Canvas坐标, 实际操作过可以, 在这里记录一下
private Vector2 WorldToScreen(Transform trans)
{
//首先找到你画布的矩形框
RectTransform CanvasRect = _canvas.GetComponent<RectTransform>();
//然后计算UI元素的位置
//0,0 for the canvas is at the center of the screen, whereas WorldToViewPortPoint treats the lower left corner as 0,0. Because of this, you need to subtract the height / width of the canvas * 0.5 to get the correct position.
Vector2 ViewportPosition = _camera.WorldToViewportPoint(trans.position);
Vector2 WorldObject_ScreenPosition = new Vector2(
((ViewportPosition.x * CanvasRect.sizeDelta.x) - (CanvasRect.sizeDelta.x * 0.5f)),
((ViewportPosition.y * CanvasRect.sizeDelta.y) - (CanvasRect.sizeDelta.y * 0.5f)));
return WorldObject_ScreenPosition;
}
转载请注明原文地址: https://ju.6miu.com/read-677330.html