- Home /
Keep Health Bar Position as it Decreases In Size
Hello, I am working on my enemy health bars. They are sprites and children to the enemy game object. There is one red bar and one black bar. To start they are the same size and at the same position. When an enemy gets hit the red bar decreases in scale on the x. So far it decreases in size correctly when attacked. The problem is that when I change the size of the red bar it no longer is aligned with the black bar to the left. This leaves black areas on both the left and right side. I would like the two bars to keep the same x position so the lost health appears on the right side. This is what I thought would accomplish this.
private GameObject healthBar;
private Transform blackHealthBar;
....
public void takeDamage(float damage){
curHealth -= damage;
if (curHealth <= 0) {
Destroy(gameObject);
}
float healthRatio = curHealth / originalHealth;
healthBar.transform.localScale = new Vector3 (originalHealthBarX * healthRatio, healthBarYScale,
healthBarZScale);
healthBar.transform.position = new Vector3 (blackHealthBar.position.x,
healthBar.transform.position.y,
healthBar.transform.position.z);
}
I thought that changing the red health bar's x position to the black health bar's x position would solve this. Both of the x positions are the same even after changing the scale of the red bar. Does anyone know how I can resolve this issue or know a different approach?
Answer by filler03 · Jan 16, 2014 at 11:14 PM
You could use Renderer.Bounds to get the left-most point of the bar before it is scaled, then scale it. Then you could get the new bounds and find the difference, which is the distance you want to then move the bar to the left.
float originalValue = renderer.bounds.min.x;
//scale the bar
float newValue = renderer.bounds.min.x;
//calculate difference
float difference = newValue - originalValue;
//move the bar to the left
transform.Translate(new Vector3(-difference, 0f, 0f);
Brilliant! Thank you works perfect! I'd up-vote your answer but I don't have enough rep!
Great, thanks ! You forgot a ) before the ; on the last line :)
Your answer
Follow this Question
Related Questions
How do i Kill Enemy with Vehicle?? 2 Answers
How to rotate a player to match the terrain slope? 0 Answers
My wave system isn't working 0 Answers
Making enemy health drop if players sword hits enemy 1 Answer
[2D]Size of an object + align on grid 2 Answers