How can I check that objects are not touching eachother?

Hello, developers.

I have a spawning system which spawns items randomly onto the map, but I am not sure how to check whether or not the item is touching another item. I have tried magnitude and .Touched but so far no luck. Here is my code:

local r = 70
function newObj(area, areaNum, tb)
	local spawner = workspace[area]
	
	local obj = objects["Area" .. areaNum][tb[math.random(1, #tb)]]:Clone()
	
	local sc = script.Script:Clone()
	sc.Parent = obj
	
	local x,z = spawner.Position.X,  spawner.Position.Z
	x,z = math.random(x - r,x + r), math.random(z - r,z + r)
	
	local pos = CFrame.new(x,spawner.Position.Y,z)
	local rot = CFrame.fromEulerAnglesXYZ(0, math.rad(math.random(0,90)), 0)
	
	obj:SetPrimaryPartCFrame(pos * rot)
	obj.Parent = workspace.Objects["Area" .. areaNum]
	sc.Disabled = false
end

for i = 10, 0, -1 do
	newObj("SpawnArea1", 1, area1obj)
end

Thank you :slight_smile:

I’d make a boolean in the spawn areas called “Occupied”, if an item spawns there it’ll make the value go true and no other items can spawn there, once that item is collected the “Occupied” boolean becomes false and items can spawn there again.

There are no spawn areas. I’m just choosing a random position on a “baseplate”.

I think you should check the distances between the objects, so basically,

local spawner = workspace[area]

for i,v in ipairs(spawner:GetChildren()) do
Here check magnitude, and see if the object is near
end

Maybe use the GetTouchingParts() method, it returns a table containing all the parts touching it.

local Touching_Parts = Part1:GetTouchingParts()

for _, v in pairs(Touching_Parts) do
If v == Part2 then
print( "Part1 is touching Part2" )
end
end
2 Likes

I don’t think that’d be a good idea if you have walls, hills, or anything that could obstruct the baseplate itself, otherwise that’ll result in things glitching into walls.

I added all the objects to a folder and also the objects that spawn into that same folder. I used @C0lvy123’s solution to check if there are any parts touching the object. If so, then re-spawn the object in a different location.