【问题标题】:How to center health bar above enemy?如何在敌人上方居中健康栏?
【发布时间】:2014-07-10 23:33:13
【问题描述】:

我有一个有效的 [某种] 健康栏,当敌人追赶你时会显示。唯一的问题是它出现在敌人脚下,偏离中心。我希望酒吧位于敌人头部上方的中心。

我知道问题出在哪里,但不知道如何解决。

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);
    }
}

【问题讨论】:

  • 这是 2d 还是 3d 游戏?你应该查一下worldtoscreenpoint,我认为它是......那么这只是将你的健康条玩家位置减半的问题......

标签: c# user-interface unity3d


【解决方案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 从上到下计数。

编辑:哈,我想我今天是你的私人导师;)

【讨论】:

  • 这一行在操作符Vector3 healthBarWorldPosition = target.transform.position + target.height;有错误说:Operator + cannot be applied to operands of type UnityEngine.Vector3 and float'
  • 哦,是的,您不能将高度直接添加到向量。最简单的解决方法可能是将高度添加为新向量。在答案中修复它:)
  • 好吧,这解决了问题,但现在栏只是在屏幕上浮动。当敌人跑下时,酒吧会浮到顶部,反之亦然。
  • 我不确定您所说的“只是在屏幕上浮动”是什么意思。但是第二部分听起来您确实需要像在原始代码中那样反转 y 位置:top = Screen.height - (healthBarScreenPosition.y + (healthBarHeight / 2)); 如果这不起作用,可以发布屏幕截图并绘制发生的情况:)
  • 哦,这一切都解决了。再次感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 1970-01-01
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 2023-02-01
相关资源
最近更新 更多