Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...