I am making keyboard controls for a camera, and I am experiencing issues regarding the innacuracy of floats. I have the variables "float Xvelocity" and "float Zvelocity", I increment these velocities by adding or subtracting the acceleration speed every time the respective direction keys are being held (A, D, W or S). However, everything I try to make the float go towards zero simply work in very strange ways. I thought it would be as simple as:
if (keys[GLFW_KEY_A] & xVelocity >-speed)
xVelocity -= acceleration / deltaTime;
if (keys[GLFW_KEY_D] & xVelocity < speed)
xVelocity += acceleration / deltaTime;
if (keys[GLFW_KEY_W] & zVelocity >-speed)
zVelocity -= acceleration / deltaTime;
if (keys[GLFW_KEY_S] & zVelocity < speed)
zVelocity += acceleration / deltaTime;
if (!keys[GLFW_KEY_A] & xVelocity<0.f) {
xVelocity+=deceleration / deltaTime;
}
if (!keys[GLFW_KEY_D] & xVelocity>0.f) {
xVelocity-=deceleration / deltaTime;
}
if (!keys[GLFW_KEY_W] & zVelocity<0.f) {
zVelocity+=deceleration / deltaTime;
}
if (!keys[GLFW_KEY_S] & zVelocity>0.f) {
zVelocity-=deceleration / deltaTime;
}
origin -= right * xVelocity;
origin -= vec3(front.x, 0.f, front.z) * zVelocity;
This doesn't make my camera completely stop moving! It does decelerate, but it rarely becomes exactly zero, thus it keeps slowly moving after releasing the key, either towards the direction it was going before or away from it. Can someone explain why doesn't this deceleration work as I intended, (probably because of float inaccuracy, but maybe it's another reason) and how may I proceed to fix it?