How would you detect how far a part is from another part?

Let’s say you have a script that places a part down when you press a button. How would you make it so it didn’t place a part down if the part it’s about to place is too close to a part that they previously placed?

1 Like

Since you’re not actually guaranteed to place it, you should instead use 3d mouse position with Mouse.Hit.p or raycast to the 3d position to get where it would be if you do place it, that way you can get that position and detect how close it is to the existing part.

local distance = (PlacingPartPosition -  ExistingPart.Position).magnitude
local requireddist = 20

if distance > requireddist then
(And now here you would run the rest of the code)
1 Like

You could store all parts you place in an empty table

local PartsPlaced = {}

function PlacePart()
    -- Function shenanigans
    table.insert(PartsPlaced, newPart)
end

You can then iterate through the table PartsPlaced and check the distance between the new intended position and all parts inside the table

local RedRadius = 10 -- The radius around previously placed parts within which you cannot place
local newPartPosition -- This would be the position where you want to place a part
local CanPlace = true
for i , part in pairs (PartsPlaced) do
    local distance = (newPartPosition - part.Position).magnitude
    if distance <= RedRadius then
        CanPlace = false
    end
end

if CanPlace then
    -- Part placing shenanigans
end

Edit: Adding to this @Forummer 's suggestion

In addition to this you should hook a function to each part’s ‘Destroying’ event/signal so that you can remove entries from the table.

local Table = {}

local function OnDestroying(Part)
	local Index = table.find(Table, Part)
	if not Index then return end
	local Value = table.remove(Table, Index)
	--Run code here if necessary.
end

Part.Destroying:Connect(function() OnDestroying(Part) end)
2 Likes