How to prevent my character from skidding due to acceleration

Godot Version

4.5

Question

Hi guys! I want my character to have some acceleration before entering its top speed so I tried modifying the basic 2D movement template:

direction = Input.get_axis("move_left", "move_right")
	if direction:
		velocity.x = move_toward(velocity.x, direction * SPEED, ACCEL*delta) 
#accel being the acceleration modifier
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)

It somewhat works. However when I quickly switch directions the character keeps some of the momentum from the initial movement making them slide a little. after using print() i figured out it’s because when you quickly switch from one direction to the other it skips the second line of code responsible for setting the velocity back to 0

Is there a way to prevent this? I am new to Godot and know almost nothing about programming so I ask for your understanding.

If I’m understanding correctly, you want to instantly set your velocity to 0 when changing direction, yes? You could just compare the signs of direction and velocity.x for that:

	if direction * velocity.x < 0.0:
		velocity.x = 0

Only when direction and velocity.x have different signs, their product will be negative. (This should probably be implemented at the beginning of the function, so you can start accelerating afterwards.)

And by the way, you probably want to change your else statement to:

	else:
		velocity.x = 0

Otherwise it can cause issues to release the move_left or move_right button before reaching the maximum speed.

1 Like

Thank you!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.