![](/img/trans.png)
[英]I made a health bar to stay above enemy but it's not always in the center of enemy
[英]How to center health bar above enemy?
我有一个运作正常的[健康]条,它会在敌人追踪您时显示。 唯一的问题是它出现在敌人脚下,偏离中心。 我希望该条位于敌人头顶上方 。
我对问题在哪里有所了解,但对如何解决却一无所知。
public float maxHealth;
public float curHealth;
public Texture2D healthBar;
private float left;
private float top;
private Vector2 playerScreen;
public Fighter player;
public Mob target;
public float healthPercent;
void Start ()
{
maxHealth = 10;
curHealth = maxHealth;
}
void Update ()
{
if(player.opponent != null) {
target = player.opponent.GetComponent<Mob>();
healthPercent = (float)target.health / (float)target.maxHealth;
} else {
target = null;
healthPercent = 0;
}
playerScreen = Camera.main.WorldToScreenPoint(target.transform.position);
left = playerScreen.x; //pretty sure right here
top = (Screen.height - playerScreen.y); //is the issue
}
void OnGUI()
{
if (target != null) {
GUI.DrawTexture(new Rect(left, top, (50 * healthPercent), 5), healthBar);
}
}
WorldToScreenPoint为您提供了模型起源的WorldPoint,我想那就是它的脚步。 因此,您要添加高度:
Vector3 healthBarWorldPosition = target.transform.position + new Vector3(0.0f, target.height, 0.0f);
healthBarScreenPosition = Camera.main.WorldToScreenPoint(healthBarWorldPosition);
其中target.height是模型的高度(可能要高一些)
这应该给您正确的高度。 对于居中部分:
left = playerScreen.x;
表示Rectangle的左端位于模型的中心。 这就是为什么它偏离中心。 您必须减去健康栏的像素大小以使其居中。
private int healthBarWidth = 50;
private int healthBarHeight = 5;
...
left = healthBarScreenPosition.x - (healthBarWidth / 2);
top = healthBarScreenPosition.y + (healthBarHeight / 2);
高度也是如此,您只需添加而不是减去,因为ScreenPoints从底部到顶部计数,而Rect从顶部到底部计数。
编辑:哈,我想我今天是你的私人老师;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.