fourthking fourthking - 1 month ago 9
C# Question

Decrease variable over a specific amount of time

So when my character gets hit by the enemies fire breath, I want to create the feel of the character being set on fire. So while the character is on fire I want him to lose a specific amount of health for a specific amount of time.

For example; lets say he is on fire for 3 seconds and I want to make him lose 30 health for being on fire, how would I evenly distribute losing 30 health for 3 seconds? I dont want the 30 damage to be applied instantly to the health, I want it to slowly tick away at the players health so that at the 3 second mark 30 damage has been dealt.

The game is being made with c#.

Thanks.

Answer Source

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.