- Home /
GUI follow enemy object
The above says it all. I am looking to have a GUI above a enemy object, so that my character camera can see enemies from far away. I am relatively new to working with the GUI functions so could someone please point me in the right direction. Thanks
Answer by robertbu · Feb 16, 2014 at 05:15 AM
Putting something from the GUI class such as using GUI.DrawTexture() above a world object is a bit complicated...partly because you have to make two coordinate changes, and partly because GUI.* stuff is anchored in the upper left corner. Let me suggest instead that you use either a GUITexture or a GUIText object. Both are created from the 'GameObject > Create Other' menu. GUITextures and GUIText object live in Viewport space. So we can use a script like this to track and object:
#pragma strict
var target : Transform;
var offset = Vector3(0.0, 0.75, 0.0);
function Update() {
var pos = target.position + offset;
transform.position = Camera.main.WorldToViewportPoint(pos);
}
You attach this script to a GUITexture. Then drag and drop the game object you want to follow on the 'target' variable.
Note when making the GUITexture, you may want to edit the Pixel Offset to set the 'Y' value to 0.0. This will anchor the GUITexture by the bottom.
Thank you this seems to work. I do have a problem though. The GUI appears where the object is, but when i turn away from the object you can still see it. Why would this be?
Thanks for the reply. This is the closest that I have got so far.
What is 'turn away' mean? If you mean turn the camera, then I cannot reproduce it. That is, if the texture follows the object so that when I turn away from the object, I no longer see the GUITexture. If you mean the object turns away, then that is how GUITextures work. If you want something to track the object and also turn with the object, then you will need to use a game object that lives in world space like a Quad.
Sorry about that. I am making a game where you fly around in an aircraft. I would like the GUI to be over an enemy aircraft. What i meant when is said "turned way" is when my plane including the camera turned away from the target. the GUI stays on the screen, even when enemy is behind me.
For a viewport coordinate, the object is in front of the camera if the 'z' is positive and behind it is negative. So you can solve this problem by adding one additional line of code:
#pragma strict
var target : Transform;
var offset = Vector3(0.0, 0.75, 0.0);
function Update() {
var pos = target.position + offset;
transform.position = Camera.main.WorldToViewportPoint(pos);
guiTexture.enabled = (transform.position.z > 0.0);
}
Thank you so much this is exactly what i wanted. Top marks to you.
Your answer
Follow this Question
Related Questions
GUI Follow RaycastHit 2 Answers
AI enemy Stuck at corners 2 Answers
Enemy's gather around the player.. How?! 2 Answers
Enemy follows player then attacks! 2 Answers
How to make an enemy stalk you 1 Answer