Smooth healthbar and softly damage

This is the code of my health bar. It works but I want it to damage smoothly but it jump. What can I do?

You can use Vector3 Lerp, Movetowards, or Smoothdamp.

1 Like

Instead of instantly affecting the value that is solely responsible for the visual feedback, you lay another layer of logic on top of that. Essentially you decouple the ‘ground truth’ from the visual feedback and introduce a “driver”.

Now your ‘ground truth’ isn’t what is actually displayed, but instead it’s the target value which the visual system uses to ‘animate’ itself. This way you can modify the style or quality of this animation without touching the ‘ground truth’.

Here’s a quick example (just a pseudocode to illustrate)

Flat update

float health = 100f;

void Update() {
  updateShownValue(health);
}

void ModifyHealth(float modifier) {
  health = Mathf.Clamp(health + modifier, 0f, 100f);
}

Animated update

float health = 100f;
float display = 0f;

void Update() {
  var changed = change(ref display, towards: health, rate: 10f);
  if(changed) updateShownValue(display);
}

void ModifyHealth(float modifier) {
  health = Mathf.Clamp(health + modifier, 0f, 100f);
}

where this helper function could be defined as

bool change(ref float value, float towards, float rate) {
  const float E = 1E-6f; // how small is too small of a difference
  var d = towards - value; // get the difference (this will have a sign)
  var ad = Mathf.Abs(d); // remove the sign
  if(ad < E) return false; // if it's near-zero abort
  value += Mathf.Clamp(Mathf.Sign(d) * rate * Time.deltaTime, -ad, ad); // * see edit below
  return true;
}

Depending on how you standardize your values (and what is your desired approach in style), you can as well use animation easing or animation curves. Or you could use other common functions as described by ArachnidAnimal above.

Edit:
The core of the function will sign the rate accordingly and scale it down to your frame time. Then it will clamp it to the actual difference, to prevent overshooting, before applying it to the displayed value.

From this you can gather that the rate is like speed in this context: it represents how much the value will [visibly] change over 1 second. Make sure it’s strictly a positive number (I didn’t want to handle this for clarity).

Edit2:
fixed a typo

Edit3:
changed ApplyDamage to ModifyHealth