Help understand movement in default CharacterBody2D script

Godot Version

4.3

Question

I’m following along Brackey’s ‘How to Make a Video Game’ tutorial on Youtube.

At 52:56 (Player 2.0) we enter our new input keys in the default script for CharacterBody2D.

Although var direction is listening for input which then applies velocity.x, I don’t see where positive x (right) or negative x (left) movement is coming from?

I don’t see how the input keys define left or right movement as they could be arbitrary strings

As the documentation says,
Get axis input by specifying two actions, one negative and one positive.

When you do Input.get_axis("move_left", "move_right"), it will detect whether or not the action move_left or move_right is pressed, and if it is, return the left direction or the right direction.

It is mostly the same as this code:

if Input.is_action_pressed("move_left"):
    direction = -1
elif Input.is_action_pressed("move_right"):
    direction = 1
else:
    direction = 0
1 Like

hey thanks @Sweep,

So is it the actual key presses that determine +x for right, -x for left?

Because there is nothing that explicitly says or connects “move_left” = -x and “move_right” = +x

Input.get_axis() is connecting move_left and move_right to direction, so when move_left is pressed the direction is -1, but when move_right is pressed the direction is 1.

You can still do things with these actions, because Input.get_axis() just checks them and returns a value.

Example:

Extends CharacterBody2D

func _physics_process(delta):
    var dir = Input.get_axis("left", "right") # If left is pressed, return -1, if right is pressed, return 1, otherwise return 0.

# Input with these actions still work, even with calling Input.get_axis().
func _input(ev):
    if Input.is_action_pressed("left"):
        print("'left' action pressed!")
    if Input.is_action_pressed("right"):
        print("'right' action pressed!
1 Like

Thanks @Sweep

1 Like