The problem here is that the player has to be holding the pickup button when they walk over the weapon. If they walk over the weapon, then try to push the pickup button, (which I'm assuming is the behavior you want) it won't work. This is because the on_area_entered()
signal that you are using is only called once when an area enters the area.
One thing I might suggest is making a script for the player's Area2D that stores the area from the signal in a variable, then making that variable null
when the on_area_exited()
signal is emitted. In the editor you can control what physics layers the player's Area is able to collide with to make sure that it only reacts to weapons, or you could add code that checks to see if the area is a weapon. Then, when the player pushes the pickup button, it uses the currently active area Here's what that might look like:
var active_area
func _on_Player_area_entered(area):
active_area = area
func _on_Player_area_exited(area):
active_area = null
func _process(delta):
if Input.is_action_just_pressed("pickup") and active_area:
# Insert weapon switch code here
To keep your code more manageable, I'd recommend making a "Weapon" script that you attach to each weapon node to define its properties, such as the slot that it takes up, its speed, its fire rate, etc. When the player picks up a weapon, you can set the player's active weapon to the weapon class defined in the pickup. This way, you'll only need to write the code for handling the pickup once, rather than for each connected signal.