Only move when jumping

Godot Version

4.3.stable.mono.official

Question

I’m pretty new to both programming and Godot. I’m trying to make a character that only moves when the jump key is being pressed. Direction can be chosen with A or D.
My current problem is that it will keep moving when the character lands after moving to one side. I’m not sure how to set the velocity to 0 after the character lands.
Here is the code I have so far:

func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta

	# Handle jump.
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		var direction := Input.get_axis("ui_left", "ui_right")
		if direction:
			velocity.x = direction * SPEED
		else:
			velocity.x = move_toward(velocity.x, 0, SPEED)
	move_and_slide()

Your character is keeping the velocity incremented by when it was not on the floor.
Add an else statement to your if not is_on_floor() that zeroes the velocity.
Something like:

if not is_on_floor():
    velocity += get_gravity() * delta
else:
    velocity.x = 0

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