Reputation: 651
This is a little difficult to explain but I want to write a piece of code that decreases the users oxygen level after a set amount of time. For example, if the user is swimming then the users oxygen level should go down .5 every 5 seconds. I have the general idea but I can not seem to figure out how to write the code. Here is what I have thus far
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;
}
Upvotes: 0
Views: 103
Reputation: 8193
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;
}
}
now all you have to do is mess with rate till you have it at a good speed.
Upvotes: 1
Reputation: 651
I figured it out, @Andrew was the closest to the answer but this is what I was looking for:
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;
}
Upvotes: 0
Reputation: 14191
Why not use a Coroutine
?
When you want to start the decrease in oxygen you can do something like this:
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;
}
}
I'm assuming that interval
is measured in seconds.
Note: I'm calling StartCoroutine
by using it's name instead of just calling the method so you can stop it later with StopCoroutine
.
Upvotes: 1