Menu
CoddyTech

Hero: Smooth Run

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

The hero starts and stops in a single frame. Make it speed up with acceleration and stop with friction:

var direction = Input.get_axis("move_left", "move_right")
if direction == 0:
	velocity.x = move_toward(velocity.x, 0, friction * delta)
else:
	velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)

Use an acceleration of 1200 and a friction of 2400. The hero reaches full speed in about a fifth of a second, so it still has room to run at the pit.

challenge icon

Challenge

Medium

Make the hero speed up and stop smoothly.

  1. Add var acceleration = 1200 and var friction = 2400.
  2. Store the axis in var direction. With no key held, move_toward velocity.x to 0 by friction * delta.
  3. With a key held, move_toward direction * speed by acceleration * delta.

Press Play: the hero gathers speed, slides a little when you stop, and clears the pit. Then Check.

Try it yourself

extends CharacterBody2D

var speed = 220
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