【发布时间】:2014-10-22 22:07:29
【问题描述】:
我正在开发一个健康栏系统,该系统会显示一个健康栏,无论敌人走到哪里都会跟随他们[效果很好]。
但我也希望在健康栏上以数字形式显示健康状况。我无法开始工作。没有错误,只是没有显示在屏幕上。
这是我的健康栏课程:
//This script works great.
public Texture2D healthBar;
public Texture2D healthBarFrame;
public float maxHealth;
public float curHealth;
private int healthBarWidth = 50;
private int healthBarHeight = 5;
private float left;
private float top;
private Vector3 healthBarScreenPosition;
public PlayerCombat player;
public Enemy target;
public float healthPercent;
void Start () {
}
void Update () {
if(player.opponent != null) {
target = player.opponent.GetComponent<Enemy>();
healthPercent = (float)target.curHealth / (float)target.maxHealth;
Vector3 healthBarWorldPosition = (target.transform.position + new Vector3(0.0f, target.transform.lossyScale.y, 0.0f));
healthBarScreenPosition = Camera.main.WorldToScreenPoint(healthBarWorldPosition);
left = healthBarScreenPosition.x - (healthBarWidth / 2);
top = Screen.height - (healthBarScreenPosition.y + (healthBarHeight / 2));
} else {
target = null;
healthPercent = 0;
}
}
void OnGUI() {
if (target != null) {
GUI.DrawTexture(new Rect(left, top, 50, 5), healthBarFrame);
GUI.DrawTexture(new Rect(left, top, (50 * healthPercent), 5), healthBar);
}
}
这是我为了显示敌人有多少HP而搞砸的(我把这段代码分成了另一个部分,这样更容易理解,通常我只是尝试将它添加到上面的脚本中。
//This is generic code taken from another user (with the variables unchanged)
public Font font;
public int fontSize = 8;
public Vector3 Offset = Vector3.zero; // The offset from the character
public Enemy target;
public PlayerCombat player;
private float health;
private TextMesh bar;
void Start()
{
target = player.opponent.GetComponent<Enemy>();
// Setup the text mesh
bar = new GameObject("HealthBar").AddComponent("TextMesh") as TextMesh;
bar.gameObject.AddComponent("MeshRenderer");
bar.gameObject.transform.parent = transform;
bar.transform.position = target.transform.position;
if(font) bar.font = font;
else bar.font = GUI.skin.font;
bar.renderer.material = font.material;
bar.characterSize = 0.25f;
bar.alignment = TextAlignment.Center;
bar.anchor = TextAnchor.MiddleCenter;
bar.fontSize = fontSize;
}
void Update()
{
target = player.opponent.GetComponent<Enemy>();
health = target.curHealth;
if(bar.text != "HP:" + health.ToString()) bar.text = "HP: " + health.ToString();
}
【问题讨论】:
标签: c# user-interface unity3d