Let me further explain my question. Let's say my Velocity is at -5.4028000 I would love it to return to zero like so.
-5.4,
-5.3,
-5.2
...
-0.2,
-0.1,
0
Same with positive numbers. For them to return to 0, In groups of 0.1's. It would return to 0, every time it was run. Because this will be placed in a update loop.
Things I have tried:
if(vx > 0)
{
vx-=0.1;
}
if(vx < 0)
{
vx+=0.1;
}
But this just locks my VX into:
VX:0.04999999
OR
VX:0.09999999
答案 0 :(得分:4)
The reason your number does not return back to zero is that the last subtraction may be subtracting a wrong number due to rounding errors. Since neither 5.4 nor 0.1 can be represented precisely in the format of double
, your last subtraction (or your last addition in case of negative numbers) would "overshoot".
This is a problem for Math.min(...)
and Math.max(...)
. Basically, we're going to only add or subtract the exact amount we need to reach zero.
if (vx > 0) {
vx -= Math.min(0.1, vx);
}
if (vx < 0) {
vx += Math.min(0.1, -vx);
}
答案 1 :(得分:0)
您需要确保最终的增量/减量不大于数字的大小:
if(vx > 0) {
vx -= Math.min(0.1, vx);
}
if(vx < 0) {
vx += Math.min(0.1, Math.abs(vx));
}
答案 2 :(得分:-1)
假设你想要每秒0.1的变化率并且不使用任何花哨的库,你可以这样做:
while (Math.abs(vx) - 0.1 > 0.0) {
vx += -Math.signum(vx) * 0.1
Thread.sleep(1000)
}
vx = 0.0;