How do i make a part repeatly spawn randomly in a part

alr so i am kinda dum and new to coding, im trying to have a bunch of parts that float up spawning randomly inside a brick that is the size of the map, i have no idea how to use math.random nor vector3 if u even need it for this. the part part the clones is inside server storage.

heres to part but i want it to be clon’ed everywhere inside a part.

i looked but i couldn’t find any solutions

where the cloned parts spawn
image

here is where the floating part is
image

this is what I have come up with to make the parts spawn in random locations within the specified area. (you will need to find the CFrame of each of the four sides of the area for this to work)

This is what the explorer looks like for me:

image

this is the script in ServerScriptService:

local floor = workspace.Floor
local part = game.ServerStorage.Part
local randtime = math.random(1,5)

while wait(randtime) do
	local rand1 = math.random(-255,255)
	local rand2 = math.random(-255,255)
	local clonepart = part:Clone()
	clonepart.Parent = workspace
	clonepart.CFrame = CFrame.new(rand1,0,rand2)
end

This is in the script inside the part to make it goy upwards:

while script.Parent.Parent == workspace do
	script.Parent.CFrame = script.Parent.CFrame + Vector3.new(0,1,0)
	wait()
end

I hope this helps you with your problem.

1 Like

If the part is some kind of cuboid it’s possible to get the bounds with the following formula: XPos-XSize/2+Part.Size.X/2 where X can be every axis and - can be +(basically back/front bounds):

local Part = workspace.Part 
local Floor = workspace.Baseplate  

function GetPositionInPart(p, object, YOffset) 
	local pos, siz1, siz2 = p.Position, p.Size, object.Size 
	
	local XMin = pos.X-siz1.X/2+siz2.X/2 
	local XMax = pos.X+siz1.X/2-siz2.X/2
	local ZMin = pos.Z-siz1.Z/2+siz2.Z/2
	local ZMax = pos.Z+siz1.Z/2-siz2.Z/2 
	
	local chosenX = math.random(XMin, XMax)
	local chosenZ = math.random(ZMin, ZMax)
	local chosenY = pos.Y+siz1.Y/2+siz2.Y/2+YOffset 
	
	local Position = Vector3.new(chosenX, chosenY, chosenZ)
	return Position 
end

--position the part, 2 studs above the ground
Part.Position = GetPositionInPart(Floor, Part, 2) 
3 Likes