Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How To Find The Nearest Attachment To Mouse?

Asked by
Ruves 21
4 years ago

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

Log in to vote
0
Answered by 4 years ago

Mouse.Target is a way.

Ad
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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.

Answer this question