Menu
CoddyTech

Speed Up Slowly

Part of the Input and Movement section of Coddy's Godot journey. Lesson 18 of 28.

The hero reaches full speed in one frame and stops in one frame. That feels stiff.

move_toward(from, to, step) moves the number from toward to by at most step, never past it. move_toward(0, 220, 15) is 15. Repeated each frame, it gives 30, 45 and so on up to 220.

Use it on velocity.x, heading for the speed the keys ask for:

var direction = Input.get_axis("move_left", "move_right")
velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)

acceleration is speed gained per second, so it gets delta. With 900, the hero reaches 220 in about a quarter of a second. With no key held, the target is 0, so the hero slows to a stop.

challenge icon

Challenge

Medium

Make the hero speed up and slow down smoothly.

  1. Store Input.get_axis("move_left", "move_right") in var direction.
  2. Set velocity.x with move_toward(velocity.x, direction * speed, acceleration * delta).

Press Play and hold an arrow: the hero gathers speed up to 220, and slows down when you let go. Then Check.

Try it yourself

extends CharacterBody2D

var speed = 220
var acceleration = 900
var gravity = 1000
var jump_velocity = -500

func _physics_process(delta):
	velocity.y += gravity * delta
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = jump_velocity
	velocity.x = Input.get_axis("move_left", "move_right") * speed
	move_and_slide()

All lessons in Input and Movement

Practice on your own: Godot playground