C# 如何将健康栏置于敌人之上?
我有一个健康栏,当敌人追击你时,它会显示出来。唯一的问题是它出现在敌人的脚下,偏离中心。我希望横杆位于敌人头部上方的中心位置 我知道问题在哪里,但不知道如何解决C# 如何将健康栏置于敌人之上?,c#,user-interface,unity3d,C#,User Interface,Unity3d,我有一个健康栏,当敌人追击你时,它会显示出来。唯一的问题是它出现在敌人的脚下,偏离中心。我希望横杆位于敌人头部上方的中心位置 我知道问题在哪里,但不知道如何解决 public float maxHealth; public float curHealth; public Texture2D healthBar; private float left; private float top; private Vector2 playerScreen; public Fighter playe
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);
}
}
公共健康;
公共卫生;
公共健康酒吧;
私人浮动左;
私人浮顶;
私人矢量2播放器屏幕;
公共拳击手;
公众暴民目标;
公众持股比例,;
无效开始()
{
maxHealth=10;
curHealth=maxHealth;
}
无效更新()
{
如果(player.ophicle!=null){
target=player.opporter.GetComponent();
healthPercent=(float)target.health/(float)target.maxHealth;
}否则{
target=null;
健康百分比=0;
}
playerScreen=Camera.main.WorldToScreenPoint(target.transform.position);
left=playerScreen.x;//这里很确定
top=(Screen.height-playerScreen.y);//是问题所在
}
void OnGUI()
{
如果(目标!=null){
DrawTexture(新的矩形(左,上,(50*healthPercent),5),healthBar);
}
}
WorldToScreenPoint为您提供了模型原点所在的世界点,我想它就在它的脚下。因此,您要向其添加高度:
Vector3 healthBarWorldPosition = target.transform.position + new Vector3(0.0f, target.height, 0.0f);
healthBarScreenPosition = Camera.main.WorldToScreenPoint(healthBarWorldPosition);
其中target.height是模型的高度(可能稍高一点)
这应该给你正确的高度。对于居中部分:
left = playerScreen.x;
表示矩形的左端位于模型的中心。这就是它偏离中心的原因。您必须减去healthbar的像素大小,使其居中
private int healthBarWidth = 50;
private int healthBarHeight = 5;
...
left = healthBarScreenPosition.x - (healthBarWidth / 2);
top = healthBarScreenPosition.y + (healthBarHeight / 2);
高度也是如此,你只需要加而不是减,因为屏幕点从下到上计数,矩形从上到下计数
编辑:哈,我想我今天是你的私人家教;) 这是2d还是3d游戏?你应该查一下worldtoscreenpoint我想它是。。。然后,只需将你的健康栏玩家位置减半……这一行在操作符
Vector3 healthBarWorldPosition=target.transform.position+target.height中有一个错误代码>错误说明:运算符+不能应用于UnityEngine.Vector3和float类型的操作数“
哦,是的,不能直接向向量添加高度。最简单的修复方法可能是将高度添加为新向量。在回答中修复了:)很好,解决了这个问题,但是现在这个条只是在屏幕上浮动。当敌人倒下时,横杆会浮到顶端,反之亦然。我不知道你所说的“只是在屏幕上漂浮”是什么意思。但是第二部分听起来确实需要像在原始代码中那样反转y位置:top=Screen.height-(healthBarScreenPosition.y+(healthBarHeight/2))代码>如果这不起作用,可能会发布一个屏幕截图,并描述发生了什么:)哦,好吧,这解决了所有问题。再次感谢:)