So i am trying to get the closest target relative to the mouse. This is done in a localscript.
i have a table:
Targets = {
["target1"] = vector2.new(0,0), -- just an example
["target2"] = vector2.new(100,0),
["target3"] = vector2.new(200,0),
["target4"] = vector2.new(300,0),
}
local mousePosition = UserInputService:GetMouseLocation() -- and i get the mousepos
So i was wondering how to know which Target is the closest to your mouse.
If you don’t understand anything, feel free to ask me!
do a loop and check if the distance is lower than the lowest distance
local UserInputService = game:GetService("UserInputService")
local Targets = {
["target1"] = Vector2.new(0,0), -- just an example
["target2"] = Vector2.new(100,0),
["target3"] = Vector2.new(200,0),
["target4"] = Vector2.new(300,0),
}
local function getNearest()
local mousePosition = UserInputService:GetMouseLocation()
local nearest, nearestDistance = nil, nil
for name, position in pairs(Targets) do
local distance = (mousePosition - position).Magnitude
if not nearestDistance or distance < nearestDistance then
nearest, nearestDistance = name, distance
end
end
return nearest, nearestDistance
end