- Home /
Why can't I divide this number by 100?
I have this line of code:
throttle += Input.GetAxis("Power") * moderation;
throttle = Mathf.Clamp(throttle, 0, 100);
throttle = Mathf.Round(throttle * 10f) / 10f;
Which simply increases the throttle value from 0-100 depending on how long you hold the "Power" button then rounds it to the nearest 10th. I then want to divide that number by 100 to get a number in a decimal percent form. eg 50% = .5
I tried using this line of code to do it:
throttle /= 100;
And
throttle *= .01
But when I add these in the maximum thrust I can get is 0.5 (Should be 100) and the outcome of those values is 0.005 (Should be 1).
What is wrong? I can't seem to figure it out.
Answer by Hoeloe · Feb 09, 2014 at 02:11 PM
Your problem is probably that you're doing calculation between 0 and 100, but then immediately converting it to between 0 and 1. This isn't in itself a problem, but you're then using the old value to calculate a new one. So, if you try two runs of this code, assuming throttle starts at 0 and you're adding, say, 10 to it each time, it does this:
throttle += Input.GetAxis("Power") * moderation;
//throttle = 10
throttle = Mathf.Clamp(throttle, 0, 100);
//throttle = 10
throttle = Mathf.Round(throttle * 10f) / 10f;
//throttle = 10
throttle /= 100;
//throttle = 0.1
That's one frames worth. Now let's look at the next frame:
//throttle = 0.1
throttle += Input.GetAxis("Power") * moderation;
//throttle = 10.1
throttle = Mathf.Clamp(throttle, 0, 100);
//throttle = 10.1
throttle = Mathf.Round(throttle * 10f) / 10f;
//throttle = 10.1
throttle /= 100;
//throttle = 0.101
What you'd actually want this to be is 0.2 at this point (you've accelerated by 10 for two frames, seems logical), but because you're reducing it by 100 each frame, the acceleration gets lessened until it's actually not at all what you expect.
To fix this, you just need another variable to store the value between 0 and 1, so you want something more like this:
throttle += Input.GetAxis("Power") * moderation;
throttle = Mathf.Clamp(throttle, 0, 100);
throttle = Mathf.Round(throttle * 10f) / 10f;
normThrottle = throttle/100;
The variable normThrottle
now has no affect on the throttle
variable, but simply keeps a log of the value, allowing you to use it later.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
C# divide float by integer 2 Answers
An OS design issue: File types associated with their appropriate programs 1 Answer