Friction
Part of the Input and Movement section of Coddy's Godot journey. Lesson 19 of 28.
Most game characters stop faster than they start. The slowing down when no key is held is friction.
To use a different number for stopping, the code needs two paths. else gives an if a second path, and exactly one of the two runs:
if direction == 0:
velocity.x = move_toward(velocity.x, 0, friction * delta)
else:
velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)== checks whether two values are equal. One = sets a variable. direction == 0 is true when no key is held.
A small friction, like 300, slides like ice. A big one, like 2400, stops in a few frames.
Challenge
MediumMake the hero stop quickly. With no key held, slow velocity.x to 0 by friction * delta per frame. With a key held, keep speeding up by acceleration.
Try it yourself
extends CharacterBody2D
var speed = 220
var acceleration = 900
var friction = 2400
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
var direction = Input.get_axis("move_left", "move_right")
velocity.x = move_toward(velocity.x, direction * speed, acceleration * delta)
move_and_slide()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground