One Axis
Part of the Input and Movement section of Coddy's Godot journey. Lesson 3 of 28.
Left and right are the two ends of one line, an axis. Input.get_axis() checks both actions and returns one number:
-1while the first action is held (left)1while the second is held (right)0when neither is held, or both
Multiply that number by the speed, and the hero moves the right way with no if:
var speed = 300
func _process(delta):
var direction = Input.get_axis("move_left", "move_right")
position.x += direction * speed * deltaWhen direction is -1, x gets smaller and the hero moves left. When it is 0, the hero stays still.
Challenge
EasyWalk the hero left and right with one line of input.
- In
_process(), storeInput.get_axis("move_left", "move_right")invar direction. - Move
position.xbydirection * speedper second.
Press Play: the arrows walk the hero at 300 pixels per second, and both at once keep it still. Then Check.
Try it yourself
extends Node2D
var speed = 300
func _process(delta):
pass
All lessons in Input and Movement
5Project: Platformer Hero
Hero: RunHero: JumpPractice on your own: Godot playground