Left and Right
Part of the Input and Movement section of Coddy's Godot journey. Lesson 2 of 28.
One if checks one action. To walk both ways, add a second if for the other action:
func _process(delta):
if Input.is_action_pressed("move_right"):
position.x += 200 * delta
if Input.is_action_pressed("move_left"):
position.x -= 200 * deltaEvery frame Godot runs both checks. Each one moves the hero only while its key is held.
Hold both keys and both lines run in the same frame. One adds 200 pixels per second, the other takes them away, so the hero stays still.
Challenge
EasyMake the hero walk left too.
- Under the first
if, add a second one that asks about"move_left". - Inside it, move the hero left at
200pixels per second.
Press Play and hold the left arrow: the hero walks left. Then Check.
Try it yourself
extends Node2D
func _process(delta):
if Input.is_action_pressed("move_right"):
position.x += 200 * delta
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground