Basic movement top down problem

Godot Versio4.5.1

Question

I have been making a game without the use of tutorials for once and have a better understanding of Godot coding, but I am still not a great architect. While the following code works with my directional movement to stop the character entirely (my desired effect) when input is more than two directions (left and up for example), it is probably the wrong/placeholder way to do it. I’ve seen other ways that choose the direction using “abs” for absolute direction, but this is not what I want considering it chooses between which direction the player will go when two inputs are simultaneously pressed. This is my original genius architecture to solve this problem. However, is there a better way?

Thank you.

if Input.is_action_pressed("left") and  Input.is_action_pressed("up"):
		direction.y = 0
		direction.x = 0
	if Input.is_action_pressed("left") and  Input.is_action_pressed("down"):
		direction.y = 0
		direction.x = 0
	if Input.is_action_pressed("right") and  Input.is_action_pressed("up"):
		direction.y = 0
		direction.x = 0
	if Input.is_action_pressed("right") and  Input.is_action_pressed("down"):
		direction.y = 0
		direction.x = 0
1 Like

Always try to minimize repetition in your code.

The problem boils down to determining if both, horizontal and vertical input components are non-zero:

var input: Vector2 = Input.get_vector("left", "right", "up", "down")
if input.x and input.y:
	direction = Vector2.ZERO

A robust version that proofs against eventual floating point precision errors would be:

var input: Vector2 = Input.get_vector("left", "right", "up", "down")
if not is_zero_approx(input.x) and not is_zero_approx(input.y)):
	direction = Vector2.ZERO

Only that it’s not really useful in OP’s case. The required condition is that both components are non-zero, so they need to be tested separately.

OK. I misread the OP so I deleted my own post.

Oh, hey. I really appreciate that. I was tinkering around with it and I am at a level where I know how to do things, but the long way around. Very cool, I will try this.

1 Like