![](/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.