Hello, I am trying to make an object spawning system for my simulator game. The problem is that the objects are able to spawn on top of each other. I have made a system that detects if two object are going to be placed close to each other, but it doesn’t seem to be working. This is the script I made:
local FunctionsModule = {}
FunctionsModule.SpawnObjects = function(Objects, Amount, Area)
local function chooseItem()
local randomNumber = math.random(1,100)
local counter = 0
for i, object in pairs(Objects) do
local weight = object.ChanceOfSpawning.Value
counter = counter + weight
if randomNumber <= counter then
return object
end
end
end
local function isPositionValid(object, position, radius, objectSpawn)
local filterObjects = {}
local boxPosition = CFrame.new(0,0,0)
local boxSize = object.Hitbox.Size
local maxObjectsAllowed = -1
local params = OverlapParams.new(filterObjects,Enum.RaycastFilterType.Include,maxObjectsAllowed,"Default")
local objectsInSpace = workspace:GetPartBoundsInBox(boxPosition,boxSize,params)
print(#objectsInSpace)
for _, part in pairs(objectsInSpace) do
print(part.Name..";"..part.Parent.Name)
if part ~= objectSpawn and part.Name ~= "Baseplate" then
return false
end
end
return true
end
for i = Amount,1,-1 do
local objectClone = chooseItem():Clone()
local objectSpawn = Area.ObjectSpawns:GetChildren()[Random.new():NextInteger(1,#Area.ObjectSpawns:GetChildren())]
local positionX = math.random(-objectSpawn.Size.x / 2, objectSpawn.Size.x / 2)
local positionZ = math.random(-objectSpawn.Size.z / 2, objectSpawn.Size.z / 2)
local point = objectSpawn.CFrame:ToWorldSpace(CFrame.new(positionX, objectClone.YPosition.Value, positionZ))
local radius = objectClone.Size.magnitude / 2
while not isPositionValid(objectClone,point.p,radius,objectSpawn) do
objectSpawn = Area.ObjectSpawns:GetChildren()[Random.new():NextInteger(1,#Area.ObjectSpawns:GetChildren())]
positionX = math.random(-objectSpawn.Size.x / 2, objectSpawn.Size.x / 2)
positionZ = math.random(-objectSpawn.Size.z / 2, objectSpawn.Size.z / 2)
point = objectSpawn.CFrame:ToWorldSpace(CFrame.new(positionX, objectClone.YPosition.Value, positionZ))
wait()
print("Retrying")
end
objectClone.Parent = Area.Objects
objectClone.CFrame = CFrame.new(point.p)
end
end
return FunctionsModule
Any help is appreciated!