0 votes

I'm watching this tutorial by heartbeast about making a rpg in godot but I can't wrap my head around how this works

func _physics_process(delta):
var input_vector = Vector2.ZERO
input_vector.x = Input.get_action_strength("right") - Input.get_action_strength("left")
input_vector.y = Input.get_action_strength("down") - Input.get_action_strength("up") 
input_vector = input_vector.normalized
Godot version Godot 3.2.3
in Engine by (12 points)

1 Answer

+1 vote

First, this code is being run every frame, because it's in the _physics_process() function.

Now, let's look at the lines one at a time:

This declares a local variable and assigns it a vector value of (0, 0).

input_vector.x = Input.get_action_strength("right") - Input.get_action_strength("left")  

This line assign the x property of input_vector to the "right" input minus the "left" input. get_action_strength() returns the "axis strength" of an input. If "right" is a key input, its strength will be 1 (when pressed) or 0 when not. If it were an analog joystick, on the other hand, the value will be something between 0 and 1, depending on how far the joystick is moved.

Subtracting left from right means the value of this is going to end up being 1 (if just "right" is held), -1 (if just "left" is held), or 0 if both are held.

input_vector.y = Input.get_action_strength("down") - Input.get_action_strength("up") 

This does the same with the vertical direction.

input_vector = input_vector.normalized()

(NOTE: Missing () added) This line takes the resulting value and normalizes it. Normalizing a vector means setting its length to 1 while keeping the direction the same. This is used so that diagonal movement ("down" and "right", for example), won't be faster, since the length of (1, 1) would be 1.414.

You can read more about how inputs work here:


by (21,940 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.