So, I haven’t really wrote anything yet for this because it’s a bit confusing to me. for this system I know that I will need to have it calculate which player is closest to it or if a character is within the attack radius, I know that I need to use DistanceFromCharacter as well. The goal is to find a player and if they are close then to do things and attack it etc. Can anyone help me with this? Also looking forward to looking into different methods everyone comes up with!
Perhaps this can help?
You think I should use raycasting instead of checking DistanceFromCharacter?
Not sure, I haven’t used raycasting before but could be helpful.
It comes down to what seems simplest to you
Well I’d think using DistanceFromCharacter would be a lot better than raycasting a ton to check if anyone is near
function GetClosest(NPCHumanoidRootPart)
local Lowest = {nil, nil}
for _, Player in ipairs(game.Players:GetPlayers()) do
local Distance = Player:DistanceFromCharacter(NPCHumanoidRootPart.Position)
if Distance == 0 then continue end
if Lowest[1] == nil or Lowest[2] == nil then
Lowest[1] = Player
Lowest[2] = Distance
continue
end
if Distance < Lowest[2] then
Lowest[1] = Player
Lowest[2] = Distance
end
end
return Lowest
end
Can you explain this a bit please?
Loop players → get the distance between player’s char and npc → check against last lowest distance → store lowest known distance & corresponding player → return lowest
also if dist is 0 then just skip because 0 is returned when player is nil
Look into pathfinding,
This will make your NPC’s stand out more.
He’ll still need to find the nearest player as u need to give params of where to go etc
To check the distance you need use Magnitude.
local Magnitude = (NPC.Position - Player.Position).Magnitude
Here you have the Magnitude on Studs.
(I write this on mobile)
as @IDontWantToBuild said use magnitude to figure the distance also
local Magnitude = (NPC.Position - Player.Position).Magnitude
if Magnitude<=10 then
print(“Player in reach”)
end
replace 10 and -10 with any distance u like
To calculate the Magnitude of all players you can use in pairs
Magnitude
will always be a positive value so it’s unnecessary to check if Magnitude >= -10
.
you are right
i always do this like
local mag=part.Position.Magnitude-plrpart.Position.Magnitude
so i get both positive and negative value
thanks i have learned something
I’m glad you learned something!
You should still use (part.Position - plrpart.Position).Magnitude
to calculate the distance between then.
part.Position.Magnitude - plrPart.Position.Magnitude
wouldn’t necessarily give you the same value.