- Home /
Problem with lifebar guiTexture duplicated
Hi to all. I'm working on a life bar for the enemies. Each enemy is correctly instantiate with his own lifebar. In the scene I have a first person controller.
Now, the problem is that if I turn 180 degrees and look behind, the life bars are duplicated almost like in a mirror. It's not an editor issue, persists in the build too. It's a camera problem I guess but I don't know how to fix it.
You can see here what happen.
The object myHealthBar is a guiTexture. The code is:
#pragma strict
// Health bar variables
var hp : float = 100;
var maxHp : float = 100;
var healthBarWidth : int;
var healthBarHeight : int;
var healthBarStretch : int;
var myHealthBar : GameObject;
var myHb : GameObject;
// Colors
var colorStart : Color;
var colorEnd : Color;
function Start ()
{
myHb = Instantiate (myHealthBar, transform.position, transform.rotation);
}
function Update ()
{
// Health bar
myHb.transform.position = camera.main.WorldToViewportPoint(transform.position);
myHb.transform.localScale = Vector3.zero;
var healthPercent : float = hp / maxHp;
if (healthPercent < 0){healthPercent = 0;}
if (healthPercent > 100){healthPercent = 100;}
healthBarStretch = healthPercent * healthBarWidth;
myHb.guiTexture.color = Color.Lerp (colorEnd, colorStart, healthPercent);
myHb.guiTexture.pixelInset = Rect(-healthBarWidth/2, 20, healthBarStretch, healthBarHeight);
damage();
}
function damage ()
{
hp = hp - .1;
if (hp < 0){hp = 0;}
}
Excuse me for my bad english, I'm italian. Thanks in advance.
Answer by whydoidoit · Jul 12, 2012 at 06:41 AM
Your problem is that WorldToViewportPoint will map the world point onto the viewport even if it is behind you (this is by design and is occasionally very useful = but often causes this problem). Don't draw your health bar when the enemy is behind you.
By the way you can test whether it is behind you by doing this:
if(Vector3.Dot(transform.forward, target.position - transform.position)>=0) {
//It's in front of you
}
Thanks for the hints. I solved the problem adding these lines.
if (inSight)
{
myHb.guiTexture.pixelInset = Rect(-healthBarWidth/2, 20, healthBarStretch, healthBarHeight);
}
else
{
myHb.guiTexture.pixelInset = Rect(0, 0, 0, 0);
}
}
function OnBecameVisible()
{
inSight = true;
}
function OnBecameInvisible()
{
inSight = false;
}
I think that this is the simplest way.
Your answer
Follow this Question
Related Questions
Multiplying GUIs 0 Answers
Triggering Main Camera Script with GUITexture 1 Answer
GuiTexture and Split Screen 1 Answer
Camera problems 2 Answers
GUI Texture - from Box to Camera 1 Answer