Hi! So I am trying to make some NPC’s and I have trouble finding a good solution to detecting nearby players. These are the solutions that I have done:
-
for loop through all players and get characters; find distance between npc and character; if character close enough, set as target
- why this is bad: i have to do this every heartbeat for better detection and looping through and doing math could take up resources
-
creating a region3 and whenever something goes in it, check if part is part of player character; if yes, then set as target
- why this is bad: When testing, I realized that you couldn’t update the region3 cframe every frame, which was a bummer. That means I have to create a new one every frame, which again can take up more resources than I want it to.
As you can see, I have a few solutions, but nothing that will satisfy my needs. Please leave any suggestions below!
Edit: I will be gone for a whole day, sorry for no reply until tomorrow.
1 Like
Try creating a hitbox(part) with no collide and with transparency. Then check when a part/object gets detected within the hitbox.
For example:
local Players = game:GetService("Players")
local Hitbox = game:GetService("Workspace")
Hitbox.Touched:Connect(Part)
local Player = Players:GetPlayerFromCharacter(Part.Parent)
if Player then
--Code here
end
end)
4 Likes
Adding onto @Logan52403’s code, you can also use the .TouchEnded event to check when the player gets out of the zone.
2 Likes
There is absolutely no reason to check every heartbeat. If you change it to check every 5 seconds that should work fine. Just take the magnitude of the distance between the NPC and all of the other characters every 5 seconds, check if any of them are close enough and then attack that player.
1 Like
Ok, I will try this solution. Thank you for the below advice also!
1 Like
Building onto this solution, 5 seconds could be too long if the player is near the NPC and you want a “press x to talk” prompt. It might be better to instead perform the check every t time where t is directly proportional to the distance the player is from the NPC.
I.e If the player is really far away, then there’s no need to check that often, maybe once every 10 seconds, but for a player that is a lot closer, maybe check every second.
Though in this case I think the hitbox idea is probably a better move.
1 Like
Thank you guys all, I’m thinking about creating an invisible Region like Region3 then use touched event too but you guys nailed it
By the way, Region3 was deprecated, use GetPartsInBox or the GetPartsInPart it’s better
1 Like
Touched Event can be buggy/inaccurate sometimes, I would suggest using Overlap Params instead.
4 Likes