Godot Version
4.3
Question
I’m trying to make an area 2d that detects if a player has entered it and if a key bind has been pressed.
Here is my code
func _on_area_2d_area_entered(area: Area2D) → void:
if area.is_in_group(“Player”):
print(“player entered!”)
if Input.is_action_just_pressed(“Use”):
queue_free()
To use multiple statements in a if
you can combine conditions with and
or or
, where and
both conditions must be true, with or
at least one condition must be true.
if area.is_in_group("Player") and Input.is_action_just_pressed("Use"):
pass
if 1 > 3 or 4 == 4:
pass
BUT
combining these conditions will not result in a interactable as you would like. Godot would only check if you pressed “Use” on the exact same frame as the player enters the area. It will not wait for the player to press “Use”.
You probably want to enable inputs when the player enters the area, and disable inputs when the player leaves. Then check for “Use” within the inputs function.
func _on_area_2d_area_entered(area: Area2D) -> void:
if area.is_in_group("Player"):
# enable inputs on enter
set_process_input(true)
func _on_area_2d_area_exited(area: Area2D) -> void:
if area.is_in_group("Player"):
# disable inputs on exit
set_process_input(false)
func _ready() -> void:
# disable inputs on start
set_process_input(false)
func _input(event: InputEvent) -> void:
# check for "Use"
if event.is_action_pressed("Use"):
self.queue_free()
i will give it a try, thanks