Unity世界坐标转屏幕坐标计算

这个是最近工作当中遇到的问题,世界坐标转Canvas坐标, 实际操作过可以, 在这里记录一下
	private Vector2 WorldToScreen(Transform trans)
        {
            //首先找到你画布的矩形框
            RectTransform CanvasRect = _canvas.GetComponent();

            //然后计算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;
        }

你可能感兴趣的:(Unity,canvas,WorldToScreen,unity)