在一段时间后减少浮动

时间:2015-07-01 19:38:11

标签: unity3d

这有点难以解释,但我想编写一段代码,在一段时间后降低用户氧气水平。例如,如果用户正在游泳,那么用户氧气水平应该每5秒降低0.5。我有一般的想法,但我似乎无法弄清楚如何编写代码。这是我到目前为止所拥有的

C#

    public float timer = 60;
    public float oxygen = 100;
    public float decreaseOxygen = 0.5f;
    public float oxygenDecreaseInterval = 2;

    private float decreaseOxyOverTime(float amountToDecrease)
    {
        oxygen = oxygen - amountToDecrease;
        return oxygen;
    }

     private float createDelayTimer()
    {
        float delayedTime = timer - oxygenDecreaseInterval;
        InvokeRepeating("delayedTime", 0, 5f);

        return delayedTime;
    }

void Update()
{

        if (timer >= createDelayTimer())
        {
            oxText.text = "Oxygen: " + decreaseOxyOverTime(decreaseOxygen) + "%";
        }

        timer -= Time.deltaTime;
}

3 个答案:

答案 0 :(得分:1)

为什么不使用Coroutine

当你想开始减少氧气时你可以这样做:

StartCoroutine("DecreaseOverTime", amountToDecreaseBy, interval);

IEnumerator DecreaseOverTime(float amountToDecreaseBy, float interval)
{
  float adjust = 0;
  while(true)
  {
   var prev = DateTime.Now;

   yield return new WaitForSeconds(interval-adjust);

   adjust = DateTime.Now.Subtract( prev ).Seconds - interval;
  }
}

我假设interval是以秒为单位测量的。

注意:我使用它的名称来呼叫StartCoroutine,而不是仅仅调用该方法,以便稍后可以使用StopCoroutine停止。

答案 1 :(得分:1)

float holdingBreath = -1f;
float delay = 5.0f;
float oxyLevel = 5.0f;
float rate = 0.5f;

void HoldBreathToggle()
{
    holdingBreath = holdingBreath > 0f ? -1f : Time.time;
}

void Update()
{
    if(holdingBreath > 0f)
    {
        if(Mathf.Approximately((Time.time - holdingBreath) % delay, 0f))
            oxyLevel -= rate;
    }
}

现在你所要做的就是乱用率,直到你的速度很快。

答案 2 :(得分:0)

我明白了,@安德鲁是最接近答案的,但这正是我所寻找的:

<强> C#

public float timer = 60;
public float oxygen = 100;
public float decreaseOxygen = 0.5f;
public float oxygenDecreaseInterval = 2;

private float compareTime = 0.0f;

private float decreaseOxyOverTime(float amountToDecrease)
{
    oxygen = oxygen - amountToDecrease;
    return oxygen;
}
void Update()
{
    compareTime += Time.deltaTime;

    timeText.text = "Time Remaining: " + timer;
    oxText.text = "Oxygen: " + oxygen + "%";

    if (compareTime >= oxygenDecreaseInterval)
    {
        compareTime = 0f;
        oxText.text = "Oxygen: " + decreaseOxyOverTime(decreaseOxygen) + "%";
    }

    timer -= Time.deltaTime;

}