how to make a chest open only once key is held and in the chests detection zone

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

extends StaticBody2D

signal chest_opened

var keytaken = false
var in_chest_zone = false

warning-ignore:unused_argument
func _on_Area2D_body_entered(body: PhysicsBody2D): #area2d - > key
if keytaken == false:
keytaken = true
$Sprite.queue_free()
warning-ignore:unused_argument

func _process(delta):
if keytaken == true:
if in_chest_zone == true:
emit_signal(“chest_opened”)

warning-ignore:unused_argument
func _on_chest_zone_body_entered(body: PhysicsBody2D): #chest zone → key
in_chest_zone = true
extends StaticBody2D

onready var only_once : bool = true
onready var animationplayer = $AnimationPlayer

func _ready():
animationplayer.play(“Idle”)

func _on_Key_chest_opened():
if only_once == true:
animationplayer.play(“Open”)
only_once = false
If the player enters the chest’s zone before having the key, the chest stays locked.
Although, as soon as the player obtains the key, the chest instantly opens.
Can anyone help me come up with a solution for this issue?
Thanks in advance!

:bust_in_silhouette: Reply From: exuin

You want to check to open the chest really only on two instances.

  1. The player obtains the key. Check if they are in the chest zone.
  2. The player enters the chest zone. Check if they have the key.

You can removed the process function. The reason the chest instantly opens when the player obtains the key is because in_chest_zone is never set to false. Set it to false when the player exists the chest zone.