0
votes

I'm having some problems with this so i thought i'd ask here.

I wrote a code that instantiates a health bar (a simple slider) and an enemy. It then sets that enemy (who just spawned) as the target of that health bar and the healthbar updates its position to always stay above the enemys head.

This is the script for the health bar (canvasRect is the rect transform of the canvas, myRect is the health bars rect transform):

private void Update() {
        if(target != null) {
            Vector2 targetPosition = Camera.main.WorldToViewportPoint(target.position);

            Vector2 screenPosition = new Vector2(((targetPosition.x * canvasRect.sizeDelta.x) - (canvasRect.sizeDelta.x * 0.5f)),
                ((targetPosition.y * canvasRect.sizeDelta.y) - (canvasRect.sizeDelta.y * 0.5f)));

            screenPosition += new Vector2(0f, 15f);

            myRect.anchoredPosition = screenPosition;
        }
    }

The script works great, but there is one problem: as you can see, i'm adding an offset in the y coordinate. This is to place the health bar above the enemy, not inside of it.

The problem comes when i move the camera however. If i zoom in, it rotates a bit (like an RTS camera) which means that the offset is wrong. The further i zoom in, the lower the health bar goes (as the offset of 15f is not enough anymore). And then when i move the camera closer to the enemy, it again pushes the health bar into him.

Is there a way to get the "border" of my enemy in screensize so i can always know what offset to have? Or is there another solution?

Thanks in advance!

1
You could try playing around with a formula involving zoom factor and offset. As you zoom out, the offset would increase accordingly (twice the zoomout, twice the offset, etc.).Neil
Create an empty gameObject, put it as child to enemy, arrange it's position above the enemy's head. And instantiate the healthbar within the empty gameObject. So that it will always stays there.Thalthanas
the zoom offset works but only until i move the camera. even if the offset is correct while zooming, once i move the camera towards the enemy, it still messes it up.Yiasmat
can i instantiate the health bar in the empty game object? i thought it has to have the canvas as it's parent or it won't render correctly?Yiasmat

1 Answers

3
votes

The solution is simple. Don't add the offset to the screen position. Instead, add it to the enemy world position (target.position + offset).

In addition to that you can get the bounds of the mesh by using MeshRenderer.bounds.