I am trying to create a terminal that uses Magnitude to detect player distance. What would be the best way to do this in a performance standpoint?
Currently this is what I am doing, however, I am afraid this may affect the game.
while true do
wait(0.5)
for _,v in pairs (game.Players:GetChildren()) do
if v.Character then
if (script.Parent.Position - v.Character.Torso.Position).Magnitude <= 12 then
print(v.Name.." is on the point!")
end
end
end
end
What you have is fine, if you want to use magnitude this in probably the best method.
If you are further concerned, you could increase the wait time, but this code in not very intense so you shouldn’t need to worry about it
One thing you can optimise is the script.Parent.Position by assigning it to a variable either inside or outside the while loop based on whether the point moves or not, but this wouldn’t have any noticeable effect at this scale.
From my understanding for i loop(Numeric Loop) is faster than using pairs or ipairs loop.
So from performance standpoint the only thing that can make this better/faster is if you used:
while true do
wait(0.5)
local players = game.Players:GetChildren()
for i = 1, #players do
if players[i].Character then
if (script.Parent.Position - players[i].Character.Torso.Position).Magnitude <= 12 then
print(players[i].Name.." is on the point!")
end
end
end
end
Better learn to like it some day. while wait is worse on performance, convention and appropriate use of API. It abuses the conditional statement, taking advantage of the fact that wait returns values. Using wait as a condition is a bad habit and it’s bad code.
while true do is correct use of a while loop, specifically in this case a non-terminating while loop.