- Home /
Getting the 2d coordinates of an object
Hey guys, I have a 3d cylinder object called "Tower" and I am trying to create a 2d rectangle health bar above it. I am trying to use
Vector3 screenPos = Camera.WorldToScreenPoint(target.position);
to get the 2d coordinates of my "Tower" which i will then use to draw a rectangle at that position. Can someone help me? Where I do put in the tower object? How do I get the coordinates of my tower object? Thanks,
Answer by zharik86 · Apr 22, 2014 at 07:08 AM
For determination of coordinates on the screen you use function WorldToScreenPoint(). But don't forget that it gives pivot point coordinates. In your case - the cylinder center. Furtherfor the health bar display, you can use either GUITexture, or GUIElements inOnGUI(). I wrote GUITexture example below (attach this script at your tower):
public GUITexture myhb = null; //your health bar for tower
void Start() {
setPosScr();
}
void Update() {
setPosScr();
}
public void setPosScr() {
Vector3 screenPos = Camera.WorldToScreenPoint(this.transform.position);
myhb.pixelInset = new Rect(screenPos.x, Screen.height - screenPos.y, myhb.pixelInset.width, mybh.PixelInset.height);
}
If you will use GUIElement tnen see my pregoing response
Answer by Burla · Apr 22, 2014 at 06:44 AM
You can access its position by doing this.
Vector3 towerPos = GameObject.Find("Tower").transform.position;
I guess the tower's position doesn't change, so you could easily do this in the Start() function, so you don't keep calling the search function which takes a lot of useage of the device.
Your answer
![](https://koobas.hobune.stream/wayback/20220613143302im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
RTS healthbar (GUI box follow GameObject) with perspective camera 1 Answer
Whats an efficient method for drawing hundreds of Health Bars etc. over units for an RTS? 2 Answers
RTS health bars 2 Answers
Adjusting returned WorldToScreenPoint for perspective angled camera 4 Answers
Whats the most efficient method for placing UI elements at world positions? (Above units etc.) 2 Answers