在特定时间内减少变量 [英] Decrease variable over a specific amount of time

查看:105
本文介绍了在特定时间内减少变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我的角色被敌人的火焰射击击中时,我想营造一种被点燃的角色的感觉.因此,当角色着火时,我希望他在特定时间内失去特定数量的健康.

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.

例如;假设他着火了3秒,我想让他因着火而失去30点生命,我将如何平均分配失去30点生命的3秒?我不希望立即对健康造成30点伤害,我希望它慢慢影响玩家的健康状况,以便在3秒标记处造成30点伤害.

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.

游戏是用c#制作的.

谢谢.

推荐答案

这就像随时间移动Gameobject 或随时间做某事.唯一的区别是您必须使用Mathf.Lerp而不是Vector3.Lerp.您还需要通过从玩家生命的当前值中减去您希望随着时间流逝而损失的值来计算最终值.您将此传递到bMathf.Lerp函数的第二个参数中.

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;
}

用法:

比方说,玩家的生命为50,我们希望在3秒之内将其删除.新玩家的生命应该在3秒后48.

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));

请注意,玩家的生命存储在newPlayerLife变量中.在协程功能结束时,您将必须使用newPlayerLife变量中的值来手动分配播放器的寿命.

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.

这篇关于在特定时间内减少变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆