How to spawn things along the surface of a sphere?

Hello,
I was wondering how I am able to get a random position along the surface of a sphere but don’t know the math behind it. Circles were easy because the surface was just the cosine and sine of the angle to get the position of the circle edge. So how would I go about getting the position of a sphere surface?

1 Like

You can achieve this using Raycasts, raycast down on the surface of the sphere and at any point a raycast hits the surface of the sphere spawn an object.

A sphere is a 3D version of a circle. A similarity between a circle and a sphere is that they both have a radius. In a sphere, any point on the sphere’s surface will always be the same distance from the sphere’s center point. (I’m referring to the sphere’s radius.)

Vectors can help you out a lot here. A vector has two pieces of information: direction and magnitude.

To get a random point on the sphere’s surface, you want a random direction, and a magnitude equal to the radius. You can use this vector from the sphere’s center to get any point on the sphere’s surface.

To ensure an equal magnitude, we can use the .Unit property of a vector, and then multiply the vector by the radius.

local sphere_center = Vector3.new(0, 0, 0)
-- This would just be the .Position property of your sphere part/mesh

local radius = 5
-- This would, most likely, be the size of your part along any axis, since all the axes of a sphere would have the same size. Although, it may vary if you are using a mesh, etc.

local random_x = math.random()
local random_y = math.random()
local random_z = math.random()

local random_vector = Vector3.new(random_x, random_y, random_z)

local random_direction = random_vector.Unit

local random_direction_with_radius = random_direction * radius

local random_point_on_surface = sphere_center + random_direction_with_radius
7 Likes

That’s a cool way of doing it. I came up with a way of getting a point on an x and y circle and used a point on that circle to then get a point on a second circle which would also simulate the same sphere surface. This looks much more simple though, thanks. Also I think you may have to edit the math.random part a bit so it can be a negative.

1 Like

Ok nice! Yeah, I think you’re right about the negative values. Good catch!

1 Like
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
	return randomPointOnSurface
end

cleaned up the code a little and added Icey’s suggestion

2 Likes