This is just like moving Gameobject over time or doing something over time. The only difference is that you have to use Mathf.Lerp
instead of Vector3.Lerp
. You also need to calculate the end value by subtracting the value you want to lose over time from the current value of the player's life. You pass this into the b
or second parameter of the Mathf.Lerp
function.
bool isRunning = false;
IEnumerator loseLifeOvertime(float currentLife, float lifeToLose, float duration)
{
//Make sure there is only one instance of this function running
if (isRunning)
{
yield break; ///exit if this is still running
}
isRunning = true;
float counter = 0;
//Get the current life of the player
float startLife = currentLife;
//Calculate how much to lose
float endLife = currentLife - lifeToLose;
//Stores the new player life
float newPlayerLife = currentLife;
while (counter < duration)
{
counter += Time.deltaTime;
newPlayerLife = Mathf.Lerp(startLife, endLife, counter / duration);
Debug.Log("Current Life: " + newPlayerLife);
yield return null;
}
//The latest life is stored in newPlayerLife variable
//yourLife = newPlayerLife; //????
isRunning = false;
}
Usage:
Let's say that player's life is 50
and we want to remove 2
from it within 3
seconds. The new player's life should be 48
after 3
seconds.
StartCoroutine(loseLifeOvertime(50, 2, 3));
Note that the player's life is stored in the newPlayerLife
variable. At the end of the coroutine function, you will have to manually assign your player's life with the value from the newPlayerLife
variable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…