So, I have a Interactive NPC, and I’d like it so when you walk up to him, a UI clones to the player so you can talk with the NPC.
Currently, I’m using “.Touched” to clone it and “.TouchEnded” to clear it.
But the issue I’m encountering is when you walk into the touchbox, sometimes the UI flashes on, then destroys even though you’re still inside the touchbox. Is there a better way I could check if a player comes within this certain range of the NPC?
On mobile
The way I go about checking if a user is in range to Npcs is by doing a distance check between the player and all of the Npcs. How I set this up is by doing this:
1.) Create a variable that will records the position of the user character.
2.) Have a loop that yields with a wait(0.3)
To keep it performance friendly.
3.) Check distance from old position to new position.
4.) If distance is >= to 4 studs then run a function that checks the distance between the player in the Npcs. (Let’s say min range is 10 studs)
5.) Don’t forget to update the new position!
6.) If the NPC is in range, apply UI changes. If not in range double check to see that the UI is actually removed.
The reason why we want to check if the players new position is at least 4 is to make sure we aren’t running any expensive Operations. In addition if the player is idle, there is no need to check distance if they are already in a conversation with said NPC.
An easy way to do this would to use this function.
:DistanceFromCharacter(Vector3)
For example:
local Player = game.Players.LocalPlayer
local NPC = workspace.NPCs.NPC
if Player:DistanceFromCharacter(NPC.PrimaryPart.Position) <= 10 then
-- Code Here
end