Unity RectTransformUtility 几个函数的详解

  • 1、 RectTransformUtility.ScreenPointToLocalPointInRectangle

public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector3 worldPoint);

根据屏幕坐标与相对矩形rect摄像机cam而言来计算出本地坐标。这个我自己实验的时候有点没搞懂。

  • 2、RectTransformUtility.ScreenPointToWorldPointInRectangle

public static bool ScreenPointToWorldPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector3 worldPoint);

根据屏幕坐标与相对矩形rect和摄像机cam而言来计算出世界坐标。很有用。通常计算UI的时候,rect带入canvas的recttransform。如果canvas 是screen overlay,则cam是null。

  • 3、RectTransformUtility.WorldToScreenPoint

Vector3 WorldToScreenPoint(Camera cam,Vector3 position);

屏幕是一个矩形,如果是一个1920*1080的屏幕,则屏幕的左下角是(0,0) ,右上角是(1920,1080)

如果物体的在一个摄像机cam1的正中心,也就是在屏幕的正中心,那么算出来的结果就是(1920/2,1080/2,z)

研究了之后,要使一个Hpbar跟着人物可以这样

先用WorldToScreenPoint 计算出ScreenPoint。 然后根据算出来的点,带入ScreenPointToWorldPointInRectangle,将得到的WorldPoint赋值给Hpbar的position。

猜你喜欢

转载自blog.csdn.net/qq_14812585/article/details/87903874