在特定时间内减少变量

因此,当我的角色被敌人的火焰呼吸击中时,我想创造出被火上浇油的角色的感觉。 因此,当角色着火时,我希望他在特定的时间内失去特定的健康状况。

例如; 让我说他已经着火了3秒钟我想让他因为着火而失去30点生命值,我将如何均匀分配失去30点生命值3秒钟? 我不希望30点伤害立即应用到健康状态,我希望它能够慢慢击退玩家的健康状况,以便在3秒内完成30点伤害。

游戏是用c#制作的。

谢谢。

这就像随着时间的推移移动Gameobject或随着时间的推移做一些事情。 唯一的区别是你必须使用Mathf.Lerp而不是Vector3.Lerp 。 您还需要通过从玩家生命的当前值中减去您想要丢失的值来计算结束值。 您将其传递给Mathf.Lerp函数的b或第二个参数。

 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秒内从中删除2 。 新玩家的生命应该在3秒后达到48

 StartCoroutine(loseLifeOvertime(50, 2, 3)); 

请注意,播放器的生命存储在newPlayerLife变量中。 在协同程序function结束时,您必须使用newPlayerLife变量中的值手动分配玩家的生命。

我想,你要找的是一个Coroutine。 在这里和这里查看文档。 它允许您与更新function分开执行自定义健康减少操作。 使用协同程序,您可以通过刻度来发生事情,并且您可以确定刻度线的时间。

你可以使用couroutines。 像这样的东西:

 void OnHitByFire() { StartCoroutine(DoFireDamage(5f, 4, 10f)); } IEnumerator DoFireDamage(float damageDuration, int damageCount, float damageAmount) { int currentCount = 0; while (currentCount < damageCount) { HP -= damageAmount; yield return new WaitForSeconds(damageDuration); currentCount++; } } 

所以这就是我最终要做的事情。 它导致火上的角色失去30点健康,你可以看到健康状况下降,而不是间隔发生。

  IEnumerator OnFire() { bool burning = true; float timer = 0; while (burning) { yield return new WaitForSeconds(0.1f); hp -= 1; timer += 0.1f; if (timer >= 3) { burning = false; } } }