• 2D
  • How can I make movement 4 directions

I am using the 2d engine and i made it so that the character can go up down left and right. However when you press more than one key he can go diagonally or doesnt change direction when you press another one while having the previous one pressed. I want to make it so he can only go right left up or down and when you press more than one key he stops. ty in advance

I am using the gdscript and the usual

... Input.is_action_pressed("ui_right") movement.x = 100 ...

6 days later

Hi

With the following code, the character will stop if two keys are pressed:

func _physics_process(delta):
    self.velocity = Vector2()
    var h_direction = 0
    var v_direction = 0

    # don't move if left and right are pressed at the same time (h_direction will be set to 0)
    h_direction = int(Input.is_action_pressed('ui_right')) - int(Input.is_action_pressed('ui_left'))
    # don't move if up and down are pressed at the same time (v_direction will be set to 0)
    v_direction = int(Input.is_action_pressed('ui_down')) - int(Input.is_action_pressed('ui_up'))

    # don't move if a "horizontal" and a "vertical" key is pressed
    if not h_direction or not v_direction:
        if h_direction:
            self.velocity.x = 100 * h_direction
        else:
           self.velocity.y = 100 * v_direction

    self.move()

Hope this helps!

4 years later

Here's another way to do it.

func _input(event):
	if event.is_pressed():
		# Get all four movement keys.
		var v = Input.get_vector('ui_left', 'ui_right', 'ui_up', 'ui_down')
		# Stop diagonals and ignore other clicks.
		if v and v == v.floor():
			movement = v * 100.0