I am making a tool that changing colors of the player’s body parts with a tool, I have not made the server-side part yet but I want to know how I can calculate the distance between the player and the target.
local mouse = game.Players.LocalPlayer:GetMouse()
if mouse.Target and mouse.Target.Parent:FindFirstChild("Humanoid") then
mouse.Target.BrickColor = BrickColor.Random()
local self = game.Players.LocalPlayer.HumanoidRootPart.Position
local target = mouse.Target.Position
local distance = (target - self).Magnitude
I haven’t done a benchmark for it in literal years, but as Magnitude involves a square-root calculation, it can (and definitely used to be!) significantly more efficient to manually calculate the sum of the Vector’s components’ squares. I.e.:
local maxDistanceSq = 25^2
local t = (target - self)
local distanceSq = t.X^2 + t.Y^2 + t.Z^2
if distanceSq > maxDistanceSq then
print("Distance more than 25 studs")
print("Distance less than or equal to 25 studs")
This is almost never a problem, and I stress that I have not checked if this is actually better in years.
A similar micro-optimization that I’m almost certain you never need to do is replacing that exponentiation with multiplication. I.e. 25*25 instead of 25^2