Spawn stuff randomly around a sphere

so the other day i was trying out egomoose’s gravity controller (cool stuff btw) and wanted to put stuff around the planet, i did some research and found this post: How to spawn things along the surface of a sphere? - #5 by Icee444. there was only a formula, so i made a script for it (wow).

local function randomPointOnSphere(center, radius)
	local randomX = (math.random()*2)-1
	local randomY = (math.random()*2)-1
	local randomZ = (math.random()*2)-1

	local randomVector = Vector3.new(randomX, randomY, randomZ)
	local randomDirection = randomVector.Unit
	local randomDirectionWithRadius = randomDirection * radius
	local randomPointOnSurface = center + randomDirectionWithRadius

	-- Adjust the randomPointOnSurface to prevent clipping inside the planet
	local distanceToSurface = (randomPointOnSurface - center).Magnitude - radius
	randomPointOnSurface = randomPointOnSurface - randomDirectionWithRadius.Unit * distanceToSurface

	return randomPointOnSurface, randomDirection -- Return the random direction as well
end

local function spawnPartsAroundSphere(spherePart, numParts)
	local radius = spherePart.Size.X / 2
	local center = spherePart.Position

	for i = 1, numParts do
		local randomPoint, randomDirection = randomPointOnSphere(center, radius) -- Get the random direction from the randomPointOnSphere function

		local part = game.ReplicatedStorage.Core:Clone()
		part.Position = randomPoint
		part.Parent = workspace
		

		-- Rotate the part to face towards the center of the sphere
		
		part.CFrame = CFrame.lookAt(part.Position, center) 
		
	end
end
while true do
	wait(10)
	spawnPartsAroundSphere(script.Parent, 5)
end



local function spawnPartsAroundSphere(spherePart, numParts)
	local radius = spherePart.Size.X / 2
	local center = spherePart.Position

	for i = 1, numParts do
		local randomPoint, randomDirection = randomPointOnSphere(center, radius) -- Get the random direction from the randomPointOnSphere function

		local part = game.ReplicatedStorage.Core:Clone()
		part.Position = randomPoint
		part.Parent = workspace
		

	
		part.CFrame = CFrame.lookAt(part.Position, center) 
		
	end
end
while true do
	wait(10)
	spawnPartsAroundSphere(script.Parent, 5)
end
3 Likes

Couldn’t you have just posted this as a reply on that topic?

1 Like

I feel like this is a bit far off from the original topic since the poster asked for specific placement of the object and never asked for the object to face the center of the object so that it always stays upright. this is mostly for planet creations and such.

they only wanted a formula so its not really an appropriate response

Please don’t do this.
Consider using the built in Random:NextUnitVector instead.

local random = Random.new()
local function randomPointOnSphere( centre: number, radius: number ): ( Vector3, Vector3 )
	local direction = random:NextUnitVector()
	return centre + direction*radius, direction
end