I'm wondering if their is a quick and easy way to find out the closest character to an object.
I'm wondering for an NPC. When you hit said NPC, it will follow you and attack. This is basically checked to see if the Health of Humanoid is lower than MaxHealth at some point, if so, You would check every players distance to see who is closer. Is their any really good ways to do this?
1) Looping through every character's torso, getting the magnitude between NPC Torso and Character torso then figuring out which player is closer than another player (I keep confusing myself on how I'd do the math to see which distance is whos, and how to math every number up until I get the smallest number, then know who that smallest number is)
2) Maybe some raycasting could be used...?
3) Perhaps Region3, if this is even useable
Please refrain from any tags being placed on the NPC when they're hit, I'm trying to check the area around the NPC or get Distances, not use tags! Any other suggestions (besides tags) would be great!
Idea #1 is good.
If you're having trouble:
local closestPlayer function getMag(p1,p2) return (p1.Magnitude - p2.Magnitude).Magnitude end function getClosest() local vals = {} for _,v in pairs (game.Players:GetChildren()) do if v.Character then vals[getMag(v.Character.Torso,script.Parent.Torso)] = v.Character end end local smallest for i,v in pairs (vals) do if smallest ~= nil and i < smallest then smallest = v end end return smallest end closestPlayer = getClosest()
Script goes into the NPC model.