Menu
CoddyTech

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:

  • -1 while the first action is held (left)
  • 1 while the second is held (right)
  • 0 when 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 * delta

When direction is -1, x gets smaller and the hero moves left. When it is 0, the hero stays still.

challenge icon

Challenge

Easy

Walk the hero left and right with one line of input.

  1. In _process(), store Input.get_axis("move_left", "move_right") in var direction.
  2. Move position.x by direction * speed per 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

Practice on your own: Godot playground