Unity中经常需要屏幕上的UI跟随物体的功能,所以分享下使用到的方法。
- 定义好主相机和界面的主Canvas,将UI的锚点设置为中间;
- 然后使用以下方式获取转换后屏幕的坐标位置,并且在Update中给UI进行位置设置;
[Header("主屏幕UI")]
public GameObject mainCanvas;
Vector3 tempPos;
public Vector3 GetWorldToScreenPosition(GameObject target)
{
tempPos = Camera.main.WorldToScreenPoint(target.transform.position);
//先获取主画布下的分辨率宽高:
RectTransform canvasRt = mainCanvas.GetComponent<RectTransform>();
float resolutionRatioWidth = canvasRt.sizeDelta.x;
float resolutionRatioHeight = canvasRt.sizeDelta.y;
//计算主画布分辨率下的宽高和屏幕的宽高的比列:
float widthRatio = resolutionRatioWidth / Screen.width;
float heightRatio = resolutionRatioHeight / Screen.height;
//计算最终屏幕2D位置坐标:
//先分别乘以宽高比值
tempPos.x *= widthRatio;
tempPos.y *= heightRatio;
//计算在中心点的屏幕坐标
tempPos.x -= resolutionRatioWidth * 0.5f;
tempPos.y -= resolutionRatioHeight * 0.5f;
// Debug.Log("屏幕位置===" + tempPos);
return tempPos;
}
//设置UI的坐标位置
void Update()
{
this.GetComponent<RectTransform>().anchoredPosition3D = GetWorldToScreenPosition();
}