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!