I have a script that spawns enemies in random positions. But they occasionally spawn inside other objects or on top of other enemies. How do I handle this problem?
local enemies = game:GetService("ReplicatedStorage").NPC.Enemies
local clonePlace = workspace.NPC.Enemies
local enemycount = script.Parent.EnemyCount
local enemytype = script.Parent.EnemyType
local maxnumber = script.Parent.MaxNumber
local delaytime = script.Parent.Delay
local increment = script.Parent.Increment
local spawner = script.Parent
while wait(delaytime.Value) do
if enemycount.Value < maxnumber.Value then
enemycount.Value = enemycount.Value + 1
local clonedEnemy = enemies:FindFirstChild(enemytype.Value):Clone()
clonedEnemy.Parent = clonePlace
local minX = spawner.Position.X - increment.Value
local maxX = spawner.Position.X + increment.Value
local minZ = spawner.Position.Z - increment.Value
local maxZ = spawner.Position.Z + increment.Value
clonedEnemy.Head.CFrame = CFrame.new( math.random(minX, maxX), spawner.Position.Y + 15, math.random(minZ, maxZ) )
end
end

2 comments
I would insert the positions into a table and every iteration you would check if the new position - any position in the table is less than 10 studs (or whatever) from your position (using magnitude) then you would retry again until it gets a new position.
That would work, and you could also spawn them in the sky and drop them until they hit the ground so that they don't spawn inside of other objects.