Detecting Entering and Exiting An Area

What is the best way to detect if a character enters and exits a certain area?

For example, when a character gets close to an NPC, I would like to show a quest gui. And when the character walks far enough away from the NPC, I would like to hide the quest gui. So I am looking for a way to do this without spamming too many events to show/hide the gui.

2 Likes

You could use Magnitide or Part.Touched or Region3 to get player area and distance. As for the spamming, you could use a debounce.

Vector3 Magnitude

Part.Touched()

Region3

4 Likes

You have options:

  • Region3
  • Touched
  • (vectorA - vectorB).magnitude – note these are Vector3 values that returns a number value
  • GetTouchingParts

Make sure to use a debounce.

Is this the end of the headers I usually make?

2 Likes

Personally I use BasePart.Touched/TouchEnded and BasePart::GetTouchingParts() to detect if something is in an area because it allows the usage of CSG and MeshParts as well. It seems to be relatively lag free if you do it correctly which is nice as well.

3 Likes

Personally, region3 would be overkill for this situation. .Touched is unreliable. Magnitude is probably the best way to go but it’s completely your choice. Run it on the client

.Touched is unreliable which is why you use it with GetTouchingParts to be 100% sure. Touched simply activates your loop to wait for the part to leave, or if you don’t mind a loop running 100% of the time you can use the .Heartbeat event of RunService to constantly check using GetTouchingParts. You’ll need to connect an empty .Touched in that case to ensure GetTouchingParts is active.

I’ve never used GetTouchingParts, wouldn’t it have the same touch registration as .Touched??
I’ll probably take a look at it on the wiki and experiment with it.

Sounds counter intuitive, but loops work really well in this situation. Simply store the NPCs and their positions in a table, then iterate through this every half a second on the client, using DistanceFromCharacter to check if you are close enough.

I originally used parts and Touched() events to display chat bubbles near NPCs, however performance issues arose from this. CompileError explains more here.

1 Like