- Home /
Rect Following Object : Unity3d
Hello everyone ,
I want to position health bar[Rect] above the enemy. I have written script for health bar[Rect] and it works as per my requirement. But as per my code, it is not coming on the top of enemy object. My enemy object is "Plane game object".
Code which i have written is as below :
#pragma strict
public var barIdle : Texture2D;
public var barFull : Texture2D;
public var initialWidth : float;
public var barRect : Rect;
public var maxHealth : float;
public var curHealth : float;
var offset = Vector2(0, 1.5);
function Start () {
}
function Update () {
var point = Camera.main.WorldToScreenPoint(transform.position + offset);
barRect = new Rect( point.x , point.y, 70, 15);
initialWidth = barRect.width;
}
function OnGUI()
{
GUI.DrawTexture(barRect, barIdle);
GUI.BeginGroup(new Rect(barRect.x, barRect.y, ((initialWidth * curHealth) / maxHealth), barRect.height));
GUI.DrawTexture(new Rect(0, 0, barRect.width, 15), barFull);
GUI.EndGroup();
Debug.Log("barRect x: " + barRect.x + " barRect y: " + barRect.y);
}
and i am attaching this script to my enemy object as i want to manage health for each enemy.
Please help me and solve my problem..
Thanks in advance for your support and help..
I assume your game is in 2D, where does the bar actually appear?
You have a fixed value for the adjustment of your bar's y position. I would suggest adjusting the y position relative to the height of your enemy
hmm i need to adjust y position of rect.. i have done Screen.height - point.y. But that does tot appear on the top..
Is your enemy a 3D object, or a 2D sprite? Do you mean that it appears behind your enemy, or below?
Answer by raimon.massanet · Oct 02, 2013 at 01:09 PM
From my understanding, the problem is that Camera.WorldToScreenPoint
returns a point, based on the bottom-left corner of the screen. That is, the bottom-left corner of the screen is (0,0)
and a higher y
means the object is further up. On the other hand, the top
parameter of the constructor for Rect
means how far away from the screen top the rectangle is, that is, the top-left corner of the screen is (0,0)
and a higher top
means the rectangle is further down.
So, your Rect
should be placed at:
barRect = new Rect(point.x, Screen.height - point.y, 70, 15);
If you solve that, your bar shold be positioned as expected.
Your answer
Follow this Question
Related Questions
Taking a hit 3 Answers
Make HUD to show object direction 0 Answers
Deduct health on collision 2 Answers
Input.mouse position on GUI Textures 2 Answers
Enemy Health GUI Issues 0 Answers