我有一个正常运作的[健康状况]栏,它会在敌人追踪您时显示。唯一的问题是它出现在敌人脚下,偏离中心。我希望该条位于敌人头顶上方。
我对问题在哪里有所了解,但对如何解决却一无所知。
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从顶部到底部计数。
编辑:哈,我想我今天是你的私人老师;)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句