Velocity instantly going from minimum to maximum.

Godot 4.4

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)

You’re saying if velocity >= maximum speed, then just set the maximum speed in the direction the player is inputting.

If maxSpeed = 100 and the player is going 120 in -x, and then inputs d, the speed will be changed to 100 in positive x.

1 Like

got any fixes?

@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

velocity.x += direction*(movespeed/3)
velocity.x = clampf(velocity.x, -max_movespeed, max_movespeed)

With this code, you don’t set it to the max value. Instead, you limit it with a negative max and a positive max.

sick man thank you