Ah, I didn’t read your question properly. Ok, then I’d change my walk function to track if the player is walking or not:
self.walking = (direction ~= 0)
I would also set the horizontal velocity based on self.facing_direction instead of direction (which may be 0):
self.velocity.x = max_speed * self.facing_direction
And in your fixed_update()
I’d look at self.walking
and if the player is no longer walking I’d apply some damping to self.velocity.x
so that it decreases over time.