My chest disappeared with me just going on it and not pressing any button

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

So I have a script that is supposed to make the chest disappear when I’m over it and then press the Interact button (E). Everything is working fine but the if doesn’t do anything. It acts like it isn’t even there. Everything is set up properly with the Input map and how the code is supposed to be layed out. So I dont really know why it doesn’t work.

func _on_Chest_area_entered(area) -> void:
print("HI")
if Input.is_action_just_pressed("Interact")== Input.is_action_just_pressed("Interact"):
	print("HI")
	self.hide()

I also tried this:

func _on_Chest_area_entered(area) -> void:
print("HI")
if Input.is_action_just_pressed("Interact"):
	print("HI")
	self.hide()

Edit: I’m dumb and didn’t read the title, whoops.
Anyway the problem with the first code is that the statement if Input.is_action_just_pressed("Interact")== Input.is_action_just_pressed("Interact") always evaluates to True, since you’re just checking if it’s equal to itself. So the object will disappear the moment you walk into it since the if statement is always True. The second code is also incorrect because Input.is_action_just_pressed() only checks if the action was just pressed the current frame. So in order to hide the chest, the player would need frame-perfect timing to press the button the same frame they entered the chest’s area.

I would suggest fixing this by not using the area_entered signal at all. Instead, have a function in the player’s script that listens for input events and then calls the hide() function on the body(ies) that it’s overlapping at the time.


Old comment (you can ignore this)
Not sure why the first code block doesn’t run properly. The if statement should always be true. You connected the signal to the function properly, right? If you did it through the Node panel you should see a green icon next to the function signature (the first line).

For the second code block, I think your problem might be a timing issue. The area entered function only executes when the player enters the chest area. So if they didn’t just press the “Interact” button the frame they entered the area, then it won’t run.

I think it would be better to not use the area entered function at all for this. Instead, have an input script in the player character to listen for the “Interact” event and then call the hide function on the body(ies) that the player is overlapping.

exuin | 2020-09-21 19:12