Move UI RectTransform to world position

Viewed 30460

I have a GameObject named Player, and a Canvas. The HealthBar GameObject is a child of the Canvas (Canvas>HealthBar). I have the HP bar following the player with a script. It is supposed to follow the player at a fixed position above it, so it sits near the top of the sprite. Here is the 'follow' part of the HP Follow Script.

        void Update () 
{
    Vector3 currentPos = transform.position;
    Vector3 playerPos = Camera.main.WorldToViewportPoint (Player.transform.position);
    transform.position = playerPos;

The problem is that the HP bar moves with the character, but at a very small fraction of the speed of which the player is moving. For example, if the player moves one unit, the bar moves 0.1 units.

Video of error: https://streamable.com/vaz7h

3 Answers

Here's the solution:

void Start () {
    Canvas.willRenderCanvases += canvasUpdate;
}

void canvasUpdate () {
    var screenPoint = RectTransformUtility.WorldToScreenPoint( canvas.worldCamera, worldPoint );
    Vector2 localPoint;
    RectTransformUtility.ScreenPointToLocalPointInRectangle( canvas.GetComponent<RectTransform>(), screenPoint, canvas.worldCamera, out localPoint );
    transform.localPosition = localPoint;
}
Related