How to calculate the closest target on your screen

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!

Use

(mouse.Position - screenPoint.Position).Magnitude

Which will give you how far away the object is from the mouse. Then cycle through the values and find the smallest one, which is the closest.

1 Like

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

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.