Issues with magnitude based generator?

Hi, I’m attempting to create a generator for my sectors of Planets in my up-coming game.
I’m currently attempting to make it so that when deciding a location for the Planet, if there is one located within a certain Magnitude, it is then re-calculated. However, as shown below, it isn’t really working too grandé.

local Sector = script.Parent

Calculate = function()
	local NewPos = Sector["Core"].Position + Vector3.new(math.random(-500, 500), 0, math.random(-500, 500))
	
	for _,Planet in pairs (Sector:GetChildren()) do
		if Planet:IsA("BasePart") and Planet.Shape == "Ball" then
			if (Planet.Position - NewPos).Magnitude < Planet.Size * .5 then
				Calculate()
			end	
		else
			break
		end
	end
	
	return NewPos
end

Generate = function()
	local RandomSize = math.random(50, 150)
	local RandomPosition = Calculate()
	if not RandomPosition then return end
	
	local Planet = Instance.new("Part")
	Planet.Shape = "Ball"
	Planet.Anchored, Planet.CanCollide = true, false
	Planet.Size = Vector3.new(RandomSize, RandomSize, RandomSize)
	Planet.CFrame = CFrame.new(RandomPosition)
	Planet.Parent = Sector
end

for i = 1, 50 do wait()
	Generate()
end
2 Likes

Perhaps you need to use more space between them by adjusting the Planet.Size * .5 part.

1 Like

Hi, I’ve attempted this by using a different range of Numbers. None worked. :pleading_face:

1 Like

Tried re-writing this with another format. Still same result.

Expectation:

My plan is for each loop to Calculate a random Offset of the sector’s position.
If (any) of the offsets generated are within a certain Magnitude of any other Planet, then they are recalculated and repeated until one generated that is not.



local Sector = script.Parent; local Core = Sector["Core"]
local P = {}

SetPos = function(Planet)
	local ReCalculate = function()
		wait(1) SetPos(Planet)
	end
	
	local Pos = Core.Position + Vector3.new(math.random(-500, 500), 0, math.random(-500, 500))
	if #P < 1 then
		table.insert(P, Pos)
		return Pos
	else
		for _,i in pairs (P) do
			if (Pos - i).Magnitude < Planet.Size.Y * 2 then
				ReCalculate(Planet)
			else
				table.insert(P, Pos)
				return Pos
			end
		end
	end
end

Generate = function()
	local RandomSize = math.random(50, 150)
	
	local Planet = Instance.new("Part")
	Planet.Size = Vector3.new(RandomSize, RandomSize, RandomSize)
	Planet.Anchored, Planet.CanCollide = true, false
	Planet.Shape = "Ball"
	Planet.Parent = Sector
	
	local _i = SetPos(Planet)
	Planet.CFrame = CFrame.new(_i)
end

for i = 1,25 do wait()
	print(i)
	Generate()
end
1 Like

Could you try recording the actual position after the planet has been created and check that list before you create another planet.
You may wish to also round up the values in the calculated position to try to remove any floating point problems.

1 Like