Walk With Velocity
Part of the Input and Movement section of Coddy's Godot journey. Lesson 8 of 28.
To walk with the keys, set the velocity from Input.get_axis() every physics frame, then move:
var speed = 200
func _physics_process(delta):
velocity.x = Input.get_axis("move_left", "move_right") * speed
move_and_slide()Holding right makes velocity.x 200. Holding left makes it -200. Holding nothing makes it 0, so the hero stops when you let go.
With a Node2D you wrote position.x += direction * speed * delta. With a body, velocity is the speed itself. Multiplying it by delta would make the hero 60 times too slow.
Challenge
EasyMake the hero walk left and right with its velocity.
- Above
move_and_slide(), setvelocity.xtoInput.get_axis("move_left", "move_right")timesspeed. - Leave out
delta:move_and_slide()applies it for you.
Press Play and hold an arrow: the hero walks at 200 pixels per second and stops when you let go. Then Check.
Try it yourself
extends CharacterBody2D
var speed = 200
func _physics_process(delta):
move_and_slide()
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground