在unity中将世界坐标转换为UGUI坐标
在2D游戏中我们需要给角色头顶添加一个血条或名字时常会用到此方法(此处用Text举例)
[SerializeField]
private Text chatText;
[SerializeField]
private GameObject player;
[SerializeField]
private RectTransform canvasRectTransform;
private float playerHeight;
Start()
{
playerHeight=player.GetComponent<Collider2D().bounds.size.y*player.transform.localScale.y;
}
private void ShowText(string text)
{
Vector3 playVec3= new Vector3(player.transform.position.x, player.transform.position.y + playerHeight, 0);
chatText.GetComponent<RectTransform>().anchoredPosition = WorldToUGUIPosition(canvasRectTransform,Camera.main,playVec3);
chatText.text = text;
}
public static Vector2 WorldToUGUIPosition(RectTransform canvasRectTransform, Camera camera, Vector3 worldPosition)
{
//世界坐标->ViewPort坐标
Vector2 viewPos = camera.WorldToViewportPoint(worldPosition);
//ViewPort坐标-〉UGUI坐标
return new Vector2(canvasRectTransform.rect.width * viewPos.x - canvasRectTransform.rect.width * 0.5f, canvasRectTransform.rect.height * viewPos.y - canvasRectTransform.rect.height * 0.5f);
}
需要拿到text要跟随的物体(player)与其父Canvas的RectTransform,需注意最后Vector2的计算方法只适用于锚点在中央的物体。
最后加上自己的显示条件,大致实现效果如下:
|