How to display text with a button press inside an area2D

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

Hi, i am newish to coding in Godot, for a while now Ive been stuck on this problem and i cant seem to find an answer on google. Is there any way i can display text after i enter an area2D. *E.G you walk over into the area and press w for the text to be displayed.
My current code for it right now is this:

For the text:

extends RichTextLabel

var Inspect = false

func _ready():
	hide()

func _on_Text_body_entered(body: Node) -> void:
		if body.name == "Player":
			if body.CanInspect:
				Inspect = true
		if Inspect:
			show()

And for the Player it is:

var CanInspect = true

	var right = Input.is_action_pressed("right")
	var left = Input.is_action_pressed("left")
	
	if right:
		vel.x += speed
		CanInspect = false
	if left:
		vel.x -= speed
		CanInspect = false 
	if Input.is_action_pressed("Inspect") and not right and not left:
		CanInspect = true
:bust_in_silhouette: Reply From: njamster

When asking a question, try to include all relevant information: how does your scene tree look like, what are the values of vel and speed, how does the player character move (move_and_collide or move_and_slide or manually?) and where is the player code you presented called: in physics_process, process or somewhere else?

That being said, here’s how I would do it:

Player.gd

extends KinematicBody2D

var inspectable_text : RichTextLabel

var vel = Vector2.ZERO
var speed = 40 # pixels / s

func _physics_process(delta):
	var right = Input.is_action_pressed("right")
	var left  = Input.is_action_pressed("left")

	if right:
		vel.x += speed
	if left:
		vel.x -= speed

	if Input.is_action_pressed("Inspect") and not right and not left and inspectable_text:
		inspectable_text.show()

    vel = move_and_slide(vel)

Text.gd

extends RichTextLabel

func _ready():
	self.hide()

func _on_Text_body_entered(body):
	if body.name == "Player":
		body.inspectable_text = self

func _on_Text_body_exited(body):
	if body.name == "Player":
		body.inspectable_text = null
		self.hide()

Checking a node’s name to determine if it’s the player or not is prone to errors btw. I would recommend using a group or a class_name for this instead.