How do I get Parts to Spawn in an Area Randomly?

Basically I want it kinda like Pet Sim99/Pet SimX Has it where it drops coins randomly, and stops when theres already a lot of coins.

The issue is, that im not sure how I can have the part spawn in an area. I know It’s something like with math.random() something like that but Im still unsure.

Iv’e tried looking on the web, solutions on the dev forum, videos, but nothing. Im not new to scripting, but Im new to spawning stuff.

I also want it to sort of spawn in the air so I can tween a bounce to the ground, which I don’t know if that will be hard or not.

Thank You!

If you would like to place a part in a random spot, simply use math.random():

local rand_x = math.random(-10, 10)
local rand_z = math.random(-10, 10)

local part = game.ServerStorage.Part:Clone()
part.Position = Vector3.new(rand_x, 5, rand_z)
part.parent = workspace

This chooses random x and z coordinates from -10 to 10 and places a cloned part at that position in the workspace at a y value of 5.

1 Like

A code for randomly throwing ores over a wide terrain based on a certain ratio. I usually do such things with AI, hope it helps you.

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Workspace = game:GetService("Workspace")

local mine = ReplicatedStorage:FindFirstChild("Mine") -- "Mine" objesini kontrol et

-- Settings klasöründen maden bulunabilirlik oranını okuma
local settingsFolder = script.Parent:WaitForChild("Settings")  -- Ayarları içeren klasör
local mineralAvailability = settingsFolder:WaitForChild("MineralAvailability")  -- "MineralAvailability" isimli IntValue
local mineralAvailabilityRate = 1 + (mineralAvailability.Value / 2)  -- 1 ile 10 arasında bir değer

local minesFolder = ReplicatedStorage:WaitForChild("Mines")  -- Ayarları içeren klasör

local miningData = {
	["Iron"] = 25,
	["Copper"] = 15,
	["Silver"] = 12,
	["Gold"] = 8,
	["Diamond"] = 3,
	["Titanium"] = 1,
	["Uranium"] = 1,
}

local spawnCount = 10
local spawnAreas = {script.Parent}

-- Raycast ile uygun bir pozisyon bulana kadar rastgele konum al
local function GetValidSpawnPosition(part)
	local maxAttempts = 10 -- En fazla 10 kez yeni pozisyon deneyelim
	for _ = 1, maxAttempts do
		local size = part.Size
		local position = part.Position

		local x = position.X + math.random(-size.X / 2, size.X / 2)
		local y = position.Y + size.Y / 2
		local z = position.Z + math.random(-size.Z / 2, size.Z / 2)
		local spawnPosition = Vector3.new(x, y, z)

		-- Raycast ile yere doğru bir kontrol yapalım
		local rayOrigin = spawnPosition
		local rayDirection = Vector3.new(0, -100, 0) -- Aşağı doğru bir raycast
		local raycastParams = RaycastParams.new()
		raycastParams.FilterType = Enum.RaycastFilterType.Exclude

		local result = Workspace:Raycast(rayOrigin, rayDirection, raycastParams)

		if result and result.Instance then
			local hitMaterial = result.Material -- Doğrudan raycast sonucunun malzemesini al

			-- Eğer suya veya havaya denk geldiysek, geçersiz say
			if hitMaterial ~= Enum.Material.Water and hitMaterial ~= Enum.Material.Air then
				return result.Position + Vector3.new(0, 1, 0) -- Madenin yere batmaması için biraz yukarıda olmasını sağlayalım
			end
		end
	end
	return nil -- Eğer uygun bir konum bulunamazsa nil döndür
end


-- Objeyi yere sabitleme (Geliştirilmiş versiyon)
local function AnchorAfterFall(object)
	local deb = false
	object.Touched:Connect(function(hit)
		if not deb and hit and hit:IsA("BasePart") then
			deb = true
			wait(0.5) -- Düşmesini bekleyelim
			if object and object.Parent then
				object.Anchored = true
				print("anchor sabit")
				object.CFrame = CFrame.new(object.Position)
			end
		end
	end)
end

-- Objeyi spawnlama
local function SpawnObject(model, spawnCount)
	if #spawnAreas == 0 then
		warn("Spawn bölgeleri bulunamadı!")
		return
	end

	local totalMinesSpawned = 0
	local spawnedMines = {}

	for name, baseChance in pairs(miningData) do
		local spawnChance = (baseChance / 100) * mineralAvailabilityRate

		for _ = 1, spawnCount do
			if math.random() < spawnChance then
				local selectedModel = minesFolder:FindFirstChild(name)
				
				if selectedModel then
					local selectedPart = spawnAreas[math.random(1, #spawnAreas)]
					local spawnPosition = GetValidSpawnPosition(selectedPart)

					if spawnPosition then
						local newObject = selectedModel:Clone()
						newObject.Parent = Workspace.Entities
						newObject.Anchored = false -- Önce düşmesine izin verelim

						if newObject:IsA("Model") and newObject.PrimaryPart then
							newObject:SetPrimaryPartCFrame(CFrame.new(spawnPosition))
							AnchorAfterFall(newObject.PrimaryPart)
						elseif newObject:IsA("BasePart") then
							newObject.CFrame = CFrame.new(spawnPosition)
							AnchorAfterFall(newObject)
						end

						spawnedMines[name] = (spawnedMines[name] or 0) + 1
						totalMinesSpawned = totalMinesSpawned + 1
					end
				end
			end
		end
	end

	print("Toplam spawn edilen maden sayısı:", totalMinesSpawned)
	for name, count in pairs(spawnedMines) do
		print(name .. ": " .. count .. " kez spawn edildi.")
	end
end

-- Spawn işlemi
SpawnObject(mine, spawnCount)

You can keep track of how many coins have spawned in a script and decide whether to spawn more based on the number.

This script should give you a baseline.

local area = regionhere -- a part
local ySpawnLevel = 20 -- gets added

function getPosition()
	local randX, randZ = Random.new():NextNumber(-area.Size.X/2, area.Size.X/2), Random.new():NextNumber(-area.Size.Z/2, area.Size.Z/2)
	local finalPos = area.Position + Vector3.new(randX, ySpawnLevel, randZ)
	return finalPos
end

If you want to do a tween, you can get the landed poisiton by doing -= vector3.new(0, ySpawnLevel, 0)

Where should I place that script?

Im pretty sure it should be placed in serverScriptservice

I figured that I just reworked the system. Instead of random spawning, I did something else. Thank you all for helping!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.