- Home /
How do i add "A" to "B" over a period of time?
So what I'm trying to do is add a pre-defined value - let's say 15 - to a current value, at a rate of let's say 0.2F per frame...and not all at once.
For example:
private float boostCharge = 0.0F public float maxBoost = 50.0F; public float boostAdd = 15.0F; public int duration = 5;
void Start () { boostCharge = maxBoost; }
void Update () { if (boostIsOn) { boostCharge--; boostCharge = Mathf.Clamp (boostCharge, 0.0F, maxBoost); } if (hitPowerUp) { boostCharge += boostAdd; // That's where I'm stuck...I want to add boostAdd to boostCharge at the rate of let's say 0.2F on every frame, instead of all at once. } }
I hope my example above is clear enough. What's the best way to achieve this? Thanks for your help!
Answer by Jesse Anders · Feb 06, 2011 at 07:06 AM
Typically you'd want to make things framerate-independent by using Time.deltaTime; as it is now, the speed of the decrease in boostCharge (and the increase, even if you scale it by a fixed amount) will depend on the framerate, which probably isn't what you want.
As for your question, a reasonable approach would be to have a boost decrease rate and a boost increase rate in units per second. Then, you would decrease like this:
boostCharge -= boostDecreaseRate * Time.deltaTime;
And increase like this:
boostCharge += boostIncreaseRate * Time.deltaTime;
You can then clamp the results or make other adjustments as needed.
Jesse thanks for your help. I think my question was a little bit confusing, as I'm already doing what you suggested, and after thinking about my problem more, I realized that what I thought I wanted to do is actually not possible, so what I'm now doing is adding 0.1F on every frame until a == b+c.
btw, quick question...if I understand correctly, then: boostCharge -= boostDecreaseRate; // is framerate dependent, and: boostCharge -= boostDecreaseRate * Time.deltaTime; // is framerate-independent. Is this correct?
Your answer