简体   繁体   English

如何在敌人上方居中放置健康栏?

[英]How to center health bar above enemy?

I have a working [sort of] health bar that displays when an enemy is pursuing you. 我有一个运作正常的[健康]条,它会在敌人追踪您时显示。 The only problem is that it shows up, off centered, at the enemy's feet. 唯一的问题是它出现在敌人脚下,偏离中心。 I would like the bar to be centered above the enemy's head. 我希望该条位于敌人头顶上方

I have an idea of where the problem is, but no idea how to fix it. 我对问题在哪里有所了解,但对如何解决却一无所知。

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 gives you the WorldPoint where your model has its origin, i guess thats at its feet. WorldToScreenPoint为您提供了模型起源的WorldPoint,我想那就是它的脚步。 So you want to add the height to it: 因此,您要添加高度:

Vector3 healthBarWorldPosition = target.transform.position + new Vector3(0.0f, target.height, 0.0f);
healthBarScreenPosition = Camera.main.WorldToScreenPoint(healthBarWorldPosition);

where target.height is the height of the model(maybe a bit more) 其中target.height是模型的高度(可能要高一些)

This should give you the correct height. 这应该给您正确的高度。 For the centered part: 对于居中部分:

left = playerScreen.x; 

says that the Rectangle has its left end at the center of your model. 表示Rectangle的左端位于模型的中心。 Thats why its off center. 这就是为什么它偏离中心。 You have to substract halt the pixel size of your healthbar to have it centered. 您必须减去健康栏的像素大小以使其居中。

private int healthBarWidth = 50;
private int healthBarHeight = 5;

...

left = healthBarScreenPosition.x - (healthBarWidth / 2);
top = healthBarScreenPosition.y + (healthBarHeight / 2);

The same holds true for the height, you just have to add instead of substract because ScreenPoints count from bottom to top and the Rect counts from top to bottom. 高度也是如此,您只需添加而不是减去,因为ScreenPoints从底部到顶部计数,而Rect从顶部到底部计数。

edit: ha, i guess i am your personal tutor today ;) 编辑:哈,我想我今天是你的私人老师;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM