Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How To Find The Nearest Attachment To Mouse?

Basically I'm trying to create an object snapping build system, I've created 4 attachments on each side of a part and I'd like to find the nearest one to the mouse when the player is hovering over the part. How would I go about doing this?

2 answers

If I understand your question correctly, you would want to use Mouse.Hit. So let's look at some way of getting the closest attachment.

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local player = Players.LocalPlayer
local mouse = player:GetMouse()

local attachments = {}

local GetAttachments = function(part)
	local itemsToCollect = {}
	for i,v in pairs(part:GetDescendants()) do 
		if v:IsA("Attachments") then 
			table.insert(itemsToCollect, v)
		end
	end
	return itemsToCollect
end

local GetClosestAttachment = function()
	if #attachments == 0 then return end 
	local closestDist = math.huge
	local closestAttach
	for i,v in pairs(attachments) do
		local mousePos = mouse.Hit.p
		local worldPos = v.WorldPosition
		local distance = (mousePos - worldPos).Magnitude
		if distance < closestDist then 
			closestDist = distance
			closestAttach= v
		end 
	end 
	return closestAttach
end 
	
RunService.RenderedStepped:Connect(function()
	local closestAttachment = GetClosestAttachment()
	if closestAttachments then 
		-- do whatever
	end 
end)

Now, this may not be at all how you are executing this, but this is a short representation of what I would do. As you'll notice, I never called the GetAttachments function, and I did this because this would be something for you to implement.

This discussion is preserved as it was. New answers, comments, and votes are closed.