[SOLVED] I made a health bar to stay above enemy but it’s not always in the center of enemy

Issue

This Content is from Stack Overflow. Question asked by Shlazar Sha

Health bar image is a children of an “Screen Space – overlay” Canvas
and it has this code inside of it

void Update()
    {
        var wantedPos = Camera.main.WorldToScreenPoint(Enemy.position);
        transform.position = new Vector3(wantedPos.x, wantedPos.y + 40, wantedPos.z);
    }

but the problem is the health bar apear above enemy but it’s not always in the center of enemy

here is a video to explain the problem more
https://youtu.be/ZMWKxJvjy2o



Solution

So looks like you are taking the centrepoint of the enemy, converting that point into screenspace, and then moving vertically up on screen to get your health bar position. It seems to work ok but u get that undesired effect.

I dont really know what you want, but you could start with a higher point in world space.

Instead of Enemy.position, make a child gameobject of the enemy that is higher up, closer to the enemies head, use that position instead of Enemy.position, and maybe reduce that 40 number.. It might be closer to what u want.


This Question was asked in StackOverflow by Shlazar Sha and Answered by Guye Incognito It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?