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

How would i find the closet part to a moving part? so it can move to the next part

Asked by
hokyboy 270 Moderation Voter
3 years ago
local NodesFolder = workspace.Nodes
local Nodes = NodesFolder:GetChildren()
local Closet

for i,v in pairs(Nodes) do
    Closet = Nodes
end

So im making a train game and i want a part to move to the closet node How would i do this? I can do the cframing i just need to know how i get the closet Node

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

You'll want to use magnitude to determine the closest part. Magnitude, in this sense, is essentially the length of a vector, and we want to find the shortest length. We'll arrive at this conclusion by subtracting the node's vector from the original position.

local OriginalPart = workspace.OriginalPart --or whatever yours is
local NodesFolder = workspace.Nodes
local Nodes = NodesFolder:GetChildren()
local Closest = nil

for i,v in pairs(Nodes) do
    local magnitude = (OriginalPart.Position - v.Position).Magnitude
    if Closest then --see if a value is already set
        if magnitude < Closest then
            Closest = magnitude
        end
    else
        Closest  = magnitude
    end
end

Ad

Answer this question