我有一个名为 Player 的游戏对象和一个 Canvas 。 HealthBar GameObject 是 Canvas (Canvas>HealthBar) 的子项。我有 HP 条跟随玩家的脚本。它应该在它上方的固定位置跟随玩家,所以它位于 Sprite 的顶部附近。 这是 HP Follow Script 的“follow”部分。
void Update ()
{
Vector3 currentPos = transform.position;
Vector3 playerPos = Camera.main.WorldToViewportPoint (Player.transform.position);
transform.position = playerPos;
问题在于 HP 条会随角色移动,但速度仅为玩家移动速度的一小部分。例如,如果玩家移动 1 个单位,则条形图移动 0.1 个单位。
最佳答案
您想使一个 UI 对象(图像)跟随一个游戏对象是 SpriteRenderer 或 MeshRenderer。
换句话说,这可以描述为将世界点转换为 UI 点。
下面这个简单的函数将世界位置转换为 UI 空间。它采用 UI 的 Canvas
作为参数,然后是您要转换为 UI 位置的位置,在您的情况下是 Player.transform.position
变量。
移动 UI 对象的键是 RectTransformUtility.ScreenPointToLocalPointInRectangle
将屏幕点转换为 ui 矩形局部点的函数。
public Vector3 worldToUISpace(Canvas parentCanvas, Vector3 worldPos)
{
//Convert the world for screen point so that it can be used with ScreenPointToLocalPointInRectangle function
Vector3 screenPos = Camera.main.WorldToScreenPoint(worldPos);
Vector2 movePos;
//Convert the screenpoint to ui rectangle local point
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvas.transform as RectTransform, screenPos, parentCanvas.worldCamera, out movePos);
//Convert the local point to world point
return parentCanvas.transform.TransformPoint(movePos);
}
用法:
public GameObject Player;
public Canvas canvas;
void Update()
{
//Convert the player's position to the UI space then apply the offset
transform.position = worldToUISpace(canvas, Player.transform.position);
}
现在,假设您已经将 UI 定位到它应该在的位置,现在您希望它跟随另一个对象(播放器),您需要使用上面的代码实现一个简单的偏移。这真的很容易。下面是它应该看起来的样子:
public GameObject Player;
public Canvas canvas;
Vector3 Offset = Vector3.zero;
void Start()
{
Offset = transform.position - worldToUISpace(canvas, Player.transform.position);
}
void Update()
{
//Convert the player's position to the UI space then apply the offset
transform.position = worldToUISpace(canvas, Player.transform.position) + Offset;
}
public Vector3 worldToUISpace(Canvas parentCanvas, Vector3 worldPos)
{
//Convert the world for screen point so that it can be used with ScreenPointToLocalPointInRectangle function
Vector3 screenPos = Camera.main.WorldToScreenPoint(worldPos);
Vector2 movePos;
//Convert the screenpoint to ui rectangle local point
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvas.transform as RectTransform, screenPos, parentCanvas.worldCamera, out movePos);
//Convert the local point to world point
return parentCanvas.transform.TransformPoint(movePos);
}
关于c# - 将 UI RectTransform 移动到世界位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45046256/