Sliding specifically to the left after a jump

Godot Version

Godot-4 4.2.1

Question

When I jump whether it’s off a wall or off the ground and I input either left or right, once I land I slow down and then begin to slide to the left perpetually.

extends CharacterBody2D

@export var gravity_magnitude = 980.0
@export var ACCELERATION = 800.0
@export var JUMP_HEIGHT = -400.0
@export var FRICTION = 800.0

func _physics_process(delta):
	if not is_on_floor():
		velocity.y += gravity_magnitude * delta

	if is_on_floor() and Input.is_action_just_pressed("up"):
		velocity.y += JUMP_HEIGHT

	velocity.x += Input.get_axis("left", "right") * ACCELERATION * delta
	
	if velocity.x < -400:
		velocity.x = -400
	
	if velocity.x > 400:
		velocity.x = 400
	
	if not Input.is_action_pressed("left") and velocity.x < 0:
		velocity.x -= -FRICTION * delta
	
	if not Input.is_action_pressed("right") and velocity.x > 0:
		velocity.x -= FRICTION * delta

	if is_on_wall() and not is_on_floor() and Input.is_action_just_pressed("up"):
		velocity = Vector2(-ACCELERATION / 2 * Input.get_axis("left", "right") , JUMP_HEIGHT - 100)
	move_and_slide()

If I change the code to

	if not Input.is_action_pressed("left") and velocity.x < 0:
		velocity.x -= -FRICTION * delta
		print(velocity.x)
	
	if not Input.is_action_pressed("right") and velocity.x > 0:
		velocity.x -= FRICTION * delta
		print(velocity.x)

the output is

0.00006135305011
-13.3332719802856
0.00006135305011
-13.3332719802856

As you can see, the velocity shifts between the two values every frame. And since the leftward acceleration is second, it always ends up moving left. I would replace the code with this:

	if is_zero_approx(Input.get_axis("left", "right")):
		velocity.x = move_toward(velocity.x, 0, FRICTION * delta)

That way it doesn’t matter what direction the player is moving.

1 Like

Thank you! I appreciate this very much!

Feel free mark @shatteredreality response above as solution.