- Home /
Problem With healthbar
HI All,
I am trying to place a health bar above the AI head, and here's the code i am using
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (GUITexture))]
public class tempBehaviour : MonoBehaviour
{
[SerializeField] private Transform target;
// Use this for initialization
void Start ()
{
if(!target)
target = transform.parent;
}
// Update is called once per frame
void Update ()
{
Vector3 wantedPos = Camera.main.WorldToViewportPoint (target.position);
transform.position = wantedPos;
}
}
Everything is working absolutely fine,the GUITexture is following the AI object wherever it goes.But the problem is when the camera is facing in opposite direction of the AI object i can still see the same GUI texture on the opposite side.
in simple terms it is actually rendering the same GUI texture twice, one above the AI Object and one exactly on the opposite side of the AI Object.
I have also cross checked that there is no other camera in scene
can anyone please help me out with this.
Answer by Coderdood · May 24, 2013 at 05:22 AM
WorldToViewportPoint we generate a similar point on the camera for objects behind the camera because it has no concept of depth. IE Both objects are still in the same spot - one is just off camera.
So try this:
[RequireComponent (typeof (GUITexture))]
public class TestGUITexture : MonoBehaviour
{
[SerializeField] private Transform target;
private GUITexture texture;
// Use this for initialization
void Start ()
{
if(!target)
target = transform.parent;
texture = (GUITexture)GetComponent(typeof(GUITexture));
}
// Update is called once per frame
void Update ()
{
Vector3 wantedPos = Camera.main.WorldToViewportPoint (target.position);
if(wantedPos.z < 0 ) { texture.enabled = false; } else { texture.enabled = true; }
transform.position = wantedPos;
}
}
By checking if the wanted position is negative we can determine whether the point is behind the camera ( see the answer to this question here ). If the point is behind the camera we can enable / disable the texture to hide it when needed.