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. Set velocity.x with move_toward, toward direction * speed, by acceleration * delta each frame.

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Input and Movement

Practice on your own: Godot playground