How would I edit a script so multiple parts spawn randomly, but don't spawn in each other?

I am trying to get multiple plants to randomly spawn while not colliding with each other.
Original model: Harvest System[For Free] v0.1.3 - YouTube

Thanks to SuchTheLegendary for the randomization system.

I need to generate multiple plants, still randomized, and also making sure they don’t collide.
Here’s the code I have now:

local SpawnLocate = workspace.PuddleFolder.SpawnPuddle

while wait(2) do
	if SpawnLocate.SpawnValue.Value == false then
		local Puddle = game.ServerStorage.PuddleStorage.WaterPuddle:Clone()
		local RandomSpawn = SpawnLocate.Position - SpawnLocate.Size/2 + Vector3.new(math.random()*SpawnLocate.Size.X, math.random()*SpawnLocate.Size.Y, math.random()*SpawnLocate.Size.Z)
		Puddle.Parent = SpawnLocate
		Puddle.Position = RandomSpawn
		Puddle.Position = Vector3.new(Puddle.Position.X, 0, Puddle.Position.Z)
		SpawnLocate.SpawnValue.Value = true
	end
	if not SpawnLocate:FindFirstChild("WaterPuddle") then
		SpawnLocate.SpawnValue.Value = false
	end
end
1 Like

You could maybe save the position of the part that spawns, and temporarily add it to a table, then when other parts spawn in they check and see if their position is equal to that position or close to it, and if its not spawn it in.

local SavedPositions = {}

local function CheckPosition(Position)
	for _, SavedPosition in ipairs(SavedPositions) do
		if (Position - SavedPosition).magnitude < 3 then -- Adjust that number to how close you are okay with parts spawning in to it, for this example I set it to 3 studs
			return true
		end
	end
	return false
end

local function SpawnPart() -- Run this to actually spawn the parts
	-- I do not know what the system you are using is, so for this example I just made a random range for the parts to spawn in
	local Position = Vector3.new(math.random(-50, 50), 5, math.random(-50, 50))

	while CheckPosition(Position) do
		Position = Vector3.new(math.random(-50, 50), 5, math.random(-50, 50))
	end

	-- Create and position the part
	local Part = Instance.new("Part")
	Part.Size = Vector3.new(5, 5, 5)
	Part.Position = Position
	Part.Anchored = true
	Part.Parent = game.Workspace

	-- Add the position to the table of saved positions
	table.insert(SavedPositions, Position)
end

3 Likes