Random Position Generation Creating Parts Outside of Expected Boundaries

I have a script, in it is a function that randomly generates a capital city within a 500x500 map radius. However, the parts aren’t being placed properly, why is this?


local function GenerateCapital(MAP_SIZE, TILE_SIZE)
	local Generated = false
	local Iteration = 0
	local RandomSeed = Random.new()
	
	if not MAP_SIZE then
		MAP_SIZE = 100
	end
	if not TILE_SIZE then
		TILE_SIZE = 5
	end
	
	repeat
		local RandomPosition = Vector3.new(RandomSeed:NextNumber(1, (MAP_SIZE * TILE_SIZE)), 10, RandomSeed:NextNumber(1, (MAP_SIZE * TILE_SIZE)))
		local PositionBeneath = Vector3.new(RandomPosition.X, -10, RandomPosition.Z)
		
		local RaycastResult = workspace:Raycast(RandomPosition, PositionBeneath)
		
		if RaycastResult then
			if RaycastResult.Instance.Name ~= "Water" and RaycastResult.Instance.Name ~= "Shallow" then
				local CapitalBuilding = script.CapitalBuilding:Clone()
				CapitalBuilding.Parent = workspace
				CapitalBuilding.Position = RaycastResult.Position-- + Vector3.new(0, CapitalBuilding.Size.Y / 2, 0)
				print(RandomPosition)
				print(PositionBeneath)
				print(RaycastResult.Position)
				Generated = true
			end
		end
		
		Iteration += 1
		
		if Iteration == 50 then
			warn("Max iterations reached! Ending execution of capital generation.")
		end
		
	until Generated == true or Iteration == 50
end

Print Output: (Notice how the actual final position is extremely far from the random position)
image

Seems it should be not “PositionBeneath” but “VectorDown” according to Raycast documentation.
So

local PositionBeneath = Vector3.new(0, -10, 0)

should work.

What is happening with the buildings ? If they are toppling and moving, set CanCollide to true before you position them and set Anchored to true after they are positioned.

CapitalBuilding.CanCollide = true
CapitalBuilding.Anchored = true

Thank you so much! This seems to have fixed the issue, I read the documentation already beforehand but I think I’m illiterate, hehehe…

Anyways, tried it out and it worked, thank you!