Problem with two keys pressed logic

Godot Version

4.5

Question

Hi, I have a character movement with keyboard. Right now I have:

  • When press right : go forward
  • When press left : go back

What I want is when both keys are down player will go where the key pressed last.

  • When holding left key then press(and hold) right key : go forward

  • When holding right key then press left key : go back

Currently I have this code but it only goes for one way only.

if Input.is_action_pressed("right") and Input.is_action_pressed("left"):
	print("BACK")
elif Input.is_action_pressed("right"):
	print("FORWARD")
elif Input.is_action_pressed("left"):
	print("BACK")

Thank you.

NVM I had this problem solved in my other project LOL

Introduce new var

var new_direction = Vector3.ZERO

Have Input register new_direction

if event.is_action_pressed("left"):
	new_direction.x = 1
elif event.is_action_pressed("right"):
	new_direction.x = -1

Then apply direction as negative new_direction so it will flip when ever new key is pressed.

	if Input.is_action_pressed("right") and Input.is_action_pressed("left"):
		direction.x -= 1
		direction.x = -new_direction.x
1 Like