Need help with rpg npc interactions

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

I have a player that is a KinematicBody2D and i need it to detect collision with multiple instances of a scene called NPC. And when it is colliding and you press enter, it will bring the textbox text (i already have a 100% working text box so thats not a problem). The thing is i’m having trouble making the player detect the collisions, can someone help me? I just need some explanation on how to do collisions.

:bust_in_silhouette: Reply From: tastyshrimp

You can either collide using areas or ray-casting. But from what you describe, I believe what you are looking for is usually done by using ray-cast, here is a link to the docs, but a simple explanation follows.

So, from what you describe you want to talk to your npc, maybe when he is in front of your character from touching to 10 units away, for example, so you don’t have to get too close to everyone you want to talk. Also you probably want to be facing the NPC you want to talk to.
A simple way to achieve this, is to have a single RayCast2D node as child of your character and facing the same direction of said the character, this way you get the rotation of the ray-cast for free.
Then, for every physics loop you check the Player input, enter is pressed, if the RayCast2D is_colliding() and if it is colliding with an NPC with get_collider(). If all that is true you show the text!
You also use the same RayCast2D, without the Enter press, to add a hint to the player that he can interact with the NPC.

It is also possible to achieve the same result with an Area2D, but differently from the ray-cast, an area will collide with all objects in range and you would have to loop through them, and make the blocking of view manually. ARayCast only detects the first Object it hits so it is usually better for such interaction detection.