简体   繁体   中英

Unity Health Bar over Enemy Head

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM