I have two float type variables. One of them is a velocity variable that moves the character upwards. The other is an acceleration variable that increases this velocity. For example:
var displacement: float = 241
var time: float = 1*60
var acceleration: Vector2 = Vector2(0, (2 * displacement) / (time * time))
var velocity: Vector2 = Vector2(0, -acceleration.y * time)
func apply():
velocity += acceleration
position += velocity
func update(delta):
apply()
In this case the current value of the acceleration variable is (0, 0.133889) and the current value of the velocity variable is (0, -8.033333).
Each time the apply() function is called, the acceleration is added to the velocity and the velocity variable, whose initial value was a negative number, starts to increase towards 0.
However, due to the floating-point problem, the value of the velocity is never exactly 0, but a number slightly larger than 0. So the acceleration continues to be added to the velocity and the velocity is added to the character's position and the character starts to move downwards this time. However, each time the character falls towards the ground, it will be lower than its initial position. In other words, the character will always stand lower than the ground the character stood on when he first started the game.
When the character falls to the ground and stops, the value of velocity is not (0, -8.033333) but (0, -8.033329). This difference of 0.000004 always prevents the character from staying in the correct position.
I'm sure game programmers have encountered this problem many times before. But I wonder how they can correctly increment/decrement float variables in such a problem. What is your solution? Thank you.