I have a velocity-based movement system for my 2D character. Sometimes if I press A(left movement input) and D(right movement input) in quick succession when i’m at max velocity in either direction, it instantly goes from negative to positive or positive to negative when it’s supposed to smoothly transition. This causes weird jolts of sudden movement in one direction.
Here’s my code:
var direction := Input.get_axis("inputkey_a", "inputkey_d")
if direction:
#direction aint 0
if abs(velocity.x) < max_movespeed:
velocity.x += direction*(movespeed/3)
else:
velocity.x = direction*max_movespeed
else:
if is_on_floor():
velocity.x = velocity.x*friction
else:
velocity.x = velocity.x*(friction+0.1)
@makaboi was right. When your absolute velocity is at the maximum, you flip the direction, but your absolute velocity is still max! “Oh, we’re now at the max velocity (but actually the wrong direction), let’s set it to the max (and now the right direction)”
A simple solution is clampf(), which returns a value constrained with a min and max limit. Replace if abs(velocity.x) < max_movespeed: with