Input.is_action_just_pressed doesn't work

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By LyguN

I’m trying to make a weapon pick-up system where the player walks in an area2d and then has the option to press F to pickup the weapon that he is currently standing over. The code looks like this:

func _on_PickupArea_area_entered(area):
  pickupText.show()
  if Input.is_action_just_pressed("pick_up"):
	 print("hello")
	 weaponIndex = area.pickupIndex
	 weapon.hide()
	 weapon = WeaponContainer.get_child(weaponIndex)
	 weapon.show()

The problem is that when I actually play the game and press the key(F), nothing happens. The signal works properly since the pickupText shows as it is supposed to. To test this out, I tried putting the same code in the _process(): function and there it actually detects when I press the action so it seems like the problem has something to do with the signal. Is it not possible to use Input statements in a signal? If so, how else can I do this?

:bust_in_silhouette: Reply From: timothybrentwood

According to your logic your player will only be able to execute the code as you expect them to if they press the “pick_up” input on the exact frame that they enter the pickup area. This is very unfeasible so you should do something along these lines:

var player_in_area 

func _unhandled_input(event: InputEvent) -> void:
	if player_in_area and event.is_action_pressed("pick_up"):
		weaponIndex = player_in_area.pickupIndex
		weapon.hide()
		weapon = WeaponContainer.get_child(weaponIndex)
		weapon.show()
        # maybe player_in_area = null

func _on_PickupArea_area_entered(area):
	pickupText.show()
	player_in_area = area

# make sure to connect the area_exited signal
func _on_PickupArea_area_exited(area):
	# pickupText.hide() or whatever your call it
	player_in_area = null

Ok this explains why it would sometimes work if I spammed the F key just as I was entering the pick-up Area. I got it working now, thanks a lot!

LyguN | 2021-12-08 12:59