Reputation: 1201
I have a variable step
which starts at 0.
Every tick I add 0.025
to the step.
step += 0.025f;
When step reaches >= 1.0
, I have reached the target position.
Movement has 4 animations, so if I divide 1 by 4, I need to increment the animation index when step reaches 0.25, 0.50, 0.75 and 1.0
The thing is, I cannot do modulus on float, and that these numbers are not exactly 0.25, 0.50 etc, I did a step print and that's what i got:
0.025
0.05
0.075
0.1
0.125
0.15
0.17500001
0.20000002
0.22500002
0.25000003
0.27500004
0.30000004
0.32500005
0.35000005
0.37500006
0.40000007
0.42500007
0.45000008
0.47500008
0.50000006
0.52500004
0.55
0.575
0.59999996
0.62499994
0.6499999
0.6749999
0.69999987
0.72499985
0.7499998
0.7749998
0.7999998
0.82499975
0.8499997
0.8749997
0.8999997
0.92499965
0.94999963
0.9749996
0.9999996
1.0249996
I don't know why for example I get 0.17500001
instead of just 0.0175
, I would like some one to explain that if possible, i'd like to know for future knowledge.
However, what else can I do to divide my animation index increment by that distance the sprite travels? I need to use that step value to calculate it.
Upvotes: 1
Views: 51
Reputation: 17454
The floating point problem is unavoidable, but there are a few work-around solutions.
Instead of checking the exact floating point value, give that value some tolerance by checking a small range.
There could be a floating point cumulative effect where after sometime it might even exceed the tolerance you set. You may round it up/down after going through n operations.
You may consider using integer, for example 25 to represent 0.025 (depending on how much precision you need).
Upvotes: 1
Reputation: 1622
Yo can always work with integers:
float valuesAsFloat = 0.325f;
int result = (int) (valuesAsFloat * 100);
int step = result / 25;
Upvotes: 2