Simpler input version

Hi!

Calling Input.is_action_pressed for all four directions seems very redundant and like something very vital for a lot of games. That’s why I was wondering if there is a better way.

While checking the docs for the Input class, I found the function Input.get_vector which takes all four direction actions at once and returns a normalized Vector2. It simplifies the code a lot and increases readability. The docs also mention WASD as a use case.

Here is my code:

func _physics_process(delta):
	var input_vector = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	velocity = input_vector * 300
	move_and_slide()
	print("velocity = " + str(velocity))

What do you think?

1 Like

I think if it makes the game work as you envisioned, with no bugs, and the control feels the way it should: use it! It makes sense, sometimes the course teachers use a simplified way that’s easy to remember, lets say “fool-proof”, or they don’t know any better themselves :smiley:

1 Like

This would work, but I would add *delta to your script in order to compensate for peoples refresh rates being different on varying machines. This is definitely aa better way to have it written, and there’s almost always a way to optimize something even further. If this sort of thing interests you I highly recommend checking out 10LOC (10 lines of code) on YouTube. They specialize in taking a game/program and reconstructing as much of it as possible in ten lines of code or less. It is wildly impressive some of the things they have achieved with such few lines. It always makes me scratch my head and realize I have such a tremendous amount of learning to do.

1 Like

You can compress it even more and save memory with one less variable if you just do this:

your solution works fine, but there are too much calls for me…
I would use a
if (Input.is_anything_pressed()):
to filter a bit to avoid unnecessary processing…

but its a slim and nice idea, thanks for that :slight_smile:

Privacy & Terms