我有一个工作[类型]健康栏,显示敌人追捕你的时间。唯一的问题是它在敌人的脚下显示出偏离中心。我希望酒吧能够集中在高于敌人的头部
。我知道问题出在哪里,但不知道如何修复它。
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);
}
}
答案 0 :(得分:1)
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从上到下计数。
编辑:哈,我想我今天是你的私人导师;)