A way to get Vector2.UP with a string "up"?

Godot Version

4.3

Question

This is not by any mean necessary, but it happens every time I write grid movement.
(It’s more complicated in the real project, please don’t fixate too much on the example.)

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("move_up"):
		position += Vector2.UP
	if event.is_action_pressed("move_down"):
		position += Vector2.DOWN
	if event.is_action_pressed("move_left"):
		position += Vector2.LEFT
	if event.is_action_pressed("move_right"):
		position += Vector2.RIGHT

Which, completely functional. But I hate it more every time I write it.
Just now, I’ve decided to try another way.

func _input(event: InputEvent) -> void:
	for dir in ["UP", "DOWN", "LEFT", "RIGHT",]:
		if event.is_action_pressed("move_" + dir.to_lower()):
			position += Vector2.?????

How do I get that?
It’s a constant under the Vector2 class, a class that…I just realized I had no idea how it works.
Vector2.get(dir) doesn’t work, Vector2.new().get(dir) either, not Vector2[dir], nor Vector2.keys()[dir], Nothing gets me the result.
Is it even possible? Or do I have to prepare another script just to use the get() function?
Thanks for reading.

i would recommend sticking to the “simple stupid” solution. better in the long run when you need to read your code again

But if you still want to write a more “factored” code, you could always create a Dictionary :

const ACTIONS : Dictionary = {
    "move_up" : Vector2.UP,
    "move_down" : Vector2.DOWN,
    "move_left" : Vector2.LEFT,
    "move_right": Vector2.RIGHT,
}

func _input(event: InputEvent) -> void:
	for action in ACTIONS:
		if event.is_action_pressed(action):
			position += ACTIONS[action]

I would also suggest looking into Input.get_vector() that would entirely remove the need to manually assign actions to direction unit vectors:

func _input(event: InputEvent) -> void:
    position += Input.get_vector(&"move_left",&"move_right",&"move_up",&"move_down")

Vector2.UP is a constant. I see no way to retrieve it via a string. As francois wrote, use a Dictionary.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.