Block not spawning where it is supposed too

Hello, I am having a problem with my script. My script is supposed to take a block and move it to a random spot within a certain bricks size and then throw the block outward. However, this works fine if the spawner is placed on the ground. Everything will spawn where it needs to be, but when I put the spawner in the air, the blocks are spawned in the air and then not even close to the spawner where I need it. Can somebody help explain why this is happening and how to fix it?

wait(math.random(1,4))
local debris = game:GetService("Debris")
local rock = script:WaitForChild("ROCK")
local ran = Random.new(tick())

rock.Parent = nil

function getPosition()
	local halfSize = script.Parent.Size * .5
	local objPos = Vector3.new(ran:NextNumber(-halfSize.X, halfSize.X), script.Parent.CFrame.Y, ran:NextNumber(-halfSize.Z, halfSize.Z))
	
	return objPos
end

function makeBLOCK()
	
	local cl = rock:Clone()
	local location = getPosition()
	
	cl.Hot.Anchored = false
	cl.Hot.Velocity = Vector3.new(math.random(-20,20), math.random(50,110), math.random(-20,20)) -- Push the blocks up and put them in different directions using velocit
	cl.Parent = script.Parent
	cl:SetPrimaryPartCFrame(CFrame.new(script.Parent.CFrame * location)
	
	debris:AddItem(cl,math.random(6,12))
end

while true do
	wait(math.random(2,7))
	--wait(1)
	
	for i = 1, math.random(1,6) do
		makeBLOCK()
	end
end
2 Likes

I believe it has something to do with

cl:SetPrimaryPartCFrame(CFrame.new(script.Parent.CFrame * location)

but I am not sure how to get the blocks to always spawn on the spawner

1 Like

Multiplying script.Parent.CFrame with location gives you a CFrame that represents location relative to script.Parent.CFrame.

This location is computed like so:

Vector3.new(ran:NextNumber(-halfSize.X, halfSize.X), script.Parent.CFrame.Y, ran:NextNumber(-halfSize.Z, halfSize.Z))

The Y component is the Y position of script.Parent.CFrame.Y. So if we look at the Y component of the CFrame you compute, we get “(script.Parent.CFrame.Y) studs above script.Parent.CFrame.Y”. In other words, the Y position + the Y position, or 2 * Y.

This explains the behavior you see. It’s fine when it’s on the ground, because 2 * a small number isn’t that far from the small number (21=2), a difference of 1, while 2 * a large number is a much bigger difference, e.g. (250 =100), a difference of 50. Much easier to notice.

The fix is this:

local objPos = Vector3.new(ran:NextNumber(-halfSize.X, halfSize.X), 0, ran:NextNumber(-halfSize.Z, halfSize.Z))
1 Like

Thank you so much! This helps.

1 Like