- Home /
Lerp sets value instantly, not interpolating it?
Hi,
I'm trying to make a health bar that fades away when the player exits combat, but appears instantly when the player enters combat. I'm using lerp to set the alpha value of the health bar objects' material, but for some reason the objects disappear instantly instead of fading away.
Here's my code:
#pragma strict
var observed : GameObject;
private var health : int;
private var inCombat : boolean;
var hearts : GameObject[];
function Update () {
health = observed.GetComponent(PlayerControlScript).health;
inCombat = observed.GetComponent(PlayerControlScript).inCombat;
for (var n : int = 0; n<hearts.length; n++) {
if (health>n) {
hearts[n].active=true;
if (inCombat) {
hearts[n].renderer.material.color.a=1.0;
} else {
hearts[n].renderer.material.color.a=Mathf.Lerp(1.0,0.0,Time.time);
}
} else {
hearts[n].active=false;
}
}
}
I can't figure out why this isn't working. :/ Thanks in advance for your help!
Answer by Chronos-L · Apr 04, 2013 at 11:32 AM
In Lerp( from, to, fraction ), the fraction should be between 0.0 and 1.0. If the fraction is 0 or smaller, then Lerp will return from
, it the fraction is 1 or larger, then Lerp will return to
. If the fraction is 0.5, then Lerp will return the value in the middle of from
and to
.
Why the color change instantly is because of that your Time.time is way larger than 1.0 when you switch back to not inCombat, so it will snap to 0.0 because the fraction is larger than 1.0.
What you should do is to establish a timer to time the interpolating:
#pragma strict
var observed : GameObject;
private var health : int;
private var inCombat : boolean;
private var pcs : PlayerControlScript;
private lerpTime : float = 0;
var hearts : GameObject[];
var fadeSpeed : float = 0.5f;
function Start() {
pcs = observed.GetComponent(PlayerControlScript);
}
function Update () {
health = pcs.health;
for (var n : int = 0; n<hearts.length; n++) {
if (health>n) {
hearts[n].active=true;
if( inCombat && inCombat != pcs.inCombat ) {
//Just exited combat mode
//Reset the lerpTime
lerpTime = 0f;
}
else if (inCombat) {
hearts[n].renderer.material.color.a=1.0;
}
else {
//Not in combat mode
lerpTime += fadeSpeed * Time.deltaTime; //Slowly increase the fraction/lerpTime
hearts[n].renderer.material.color.a=Mathf.Lerp(1.0,0.0,lerpTime );
}
} else {
hearts[n].active=false;
}
}
inCombat = pcs.inCombat;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613095653im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Black dots when changed the alpha of the material 0 Answers
Easy sprite finding script 1 Answer
Health bar goes negative 2 Answers