- Home /
Sometime when I subract a value to hit zero I get a -1
So this might be for best practices too but I have a value that is a float value. I have the float value subtracting going backwards until it hits zero but maybe 1 out of 20 times it will give me a value of -1. What call or function would be best to use to avoid this problem from ever occuring. Once it hits 0 to stop subtracting then I have another check that if floatValue =less than 0 to then floatValue = 0. (I'm asking this question on my phone since I'm away from my computer at the moment and there is apparently no less than sign on my keyboard lol.) I'd like to know as this has me puzzle I'm still trying to learn about coding and maybe someone could help me with general best practices in this case to be a better programmer. Thanks again.
Answer by metalted · Jul 15, 2019 at 09:03 PM
When you are subtracting floats using for instance Time.deltaTime, it will never land on 0, it will always overshoot. So in your code you check if its smaller than 0 instead of checking if its equal, because that will not work. Sometimes it might overshoot so much that it will be rounded to -1 instead of 0. There isn't a single way to correct this. The only thing that is sure, is that you have to handle it on the moment it happens. So when your if statement checks if it is smaller than 0 and its true, just set the value to 0:
if(timerValue < 0)
{
timerValue = 0;
//Code...
}
If it is a timer you are using, you could also have a float timer and an int timer. The float timer will be the actual counter, and the int timer will be a rounded version of the float timer. That way it will always be exactly 0 and the problem is gone: float timer = 10; int roundedTimer;
public void Update()
{
timer -= 1 * Time.deltaTime;
roundedTimer = Mathf.FloorToInt(timer);
if(roundedTimer == 0)
{
//Do something...
}
}
A side effect of this though, is that the rounded value (depending on if you Ceil, Floor or Round) will never be the same as the actual value and will be wrong by 0.5 seconds max. Maybe if you don't have an if statement but you still don't want it to overshoot, you could use something like this:
float timer = 10;
public void Update()
{
timer -= 1 * Time.deltaTime;
timer = Mathf.Max(timer, 0);
//Do something
}
So as you can see, there are many ways to handle the situation. There is no way you must do it. Just make sure you handle it, before you use the data.
Thank you for helping out , I have tried the last suggestion, I will post back in a few days as I continue to test and see if that fixes the problem as I suspect it will.
Your answer
Follow this Question
Related Questions
Alternative to Update 1 Answer
float changes sign randomly 0 Answers
How can I make this only act once? 3 Answers
Character moves off to side and floats 0 Answers
Have slider subtract from one variable to add to itself. 0 Answers