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
MediumMake the hero speed up and stop smoothly.
- Add
var acceleration = 1200andvar friction = 2400. - Store the axis in
var direction. With no key held,move_towardvelocity.xto0byfriction * delta. - With a key held,
move_towarddirection * speedbyacceleration * 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
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground