世界坐标转屏幕坐标

世界坐标转屏幕坐标,
目的
UI层的物体能跟随3D世界的物体
应用场景
血条,聊天气泡,物体小提示

转换坐标

        private Vector2 GetScreenPosition(Vector3 worldPosition)
        {
    
    
            Vector2 anchoredPosition = _camera.WorldToScreenPoint(worldPosition);
            anchoredPosition *= CanvasHelper.RootCanvasSize.x / Screen.width;
            float newWidth = anchoredPosition.x - CanvasHelper.RootCanvasSize.x * 0.5f;
            float newHeight = anchoredPosition.y - CanvasHelper.RootCanvasSize.y * 0.5f;
            return new Vector2(newWidth, newHeight);
        }

在update里更新

  		public void OnUpdate()
        {
    
    
            if (_target != null && CharacterController.Instance != null)
            {
    
    
                rectTransform.anchoredPosition = GetScreenPosition(_target.position);
            }
        }

猜你喜欢

转载自blog.csdn.net/hhh314159/article/details/134207514