Monday, March 2, 2015

Unreal notes: health bar system

I was requested to make a health bar system in UE4 that:
1. Correctly shows the enemy's remaining health percentage
2. Changes transparency based on the distance between player and enemy
3. Has this "shrinking animation" so when enemy takes a chunk of damage, rather than having its health value "jump back", it has the part between original health value and current health value changes color, then the part with different color will shrink until it disappears

So, how do you do that?

 To make a "shrinking effect", it is better to draw two different health bars, one under another. To explain it more clearly, let's assume the top bar is green, the bottom bar is red, enemy health bar will normally appear green, and have a red "shrinking" part when damaged.
Now we just set the green bar's value to enemy's current health and update it every tick, so the green bar will always reflect enemy's real health value. When enemy gets hit, it will suddenly decreases, and expose the red bar underneath.
For the red bar, we just need to check if its value is bigger than the green bar.If the value is bigger, set red bar's value to decrease at a constant speed, until the two values are equal. (Probably can have a picture here when I get to the lab)
If you also want a dark box underneath your health bar, don't use the unreal setting as you won't be able to adjust its transparency later, use a separate health bar, put it at the bottom, and fill it with whatever color you want.

Note that we need to keep a reference to the NPC object inside our widget so we can get the correct health value inside widget's tick function, we will also need the reference later to update transparency.

To update transparency, we calculate the distance from player to the actor we kept a reference of, clamp it between X and Y, where X is the maximum distance where alpha = 1, and Y is the smallest distance where alpha = 0, then calculate alpha = (distance-X)/Y, and use "set fill color and transparency" to set alpha, keep in mind you have to set color too.

For the having widgets showing up part, I found this tutorial works much better than the 3D health bar tutorial on youtube. Since it will be outdated pretty soon, I will not go into detail about it.

(Note to self: add pics later to explain things)
  

No comments:

Post a Comment