Raycasting Spawning Outside of Zone

Hey! So far I’ve been learning basics of the Raycasting Feature and so far I understand the certain basics of it, but however I’m now wanting to fix this issue with them spawning out of the zone, however the code I’ve used was from basic understanding however if I change my raycast direction it’ll result in a nil instance that cannot give out the result of how I wanted it. I’ve very new to this however, and would appreciate the help. I’ve tried looking around in the Roblox-Developer Forum to find solutions but I’ve never found any answer to fix this I’m not trying to use another way for spawning in regions because I want it to spawn in different random positions while the spawning does not spawn into walls or floors for that matter, I want to make a advanced spawning coin system, however there is only 1 solution I found but that requires a module when I want to learn my own understanding, I would love atleast support that could help me understand what I’m lacking to know of and could use for this to be advanced and correctly spawning :slight_smile:


Spawning outside of the zone:
Screenshot 2022-05-20 102735

This is the code so far.

local Region = workspace:WaitForChild("SpawnPosition");
local SpawnFolder = workspace:WaitForChild("Spawners");

local PosX, PosZ = Region.Position.X, Region.Position.Z

while wait(.5) do
	local SizeX, SizeZ = Region.Size.X / 2, Region.Size.Z / 2
	local Position1 = math.random(PosX - SizeX, PosX + SizeX)
	local Position2 = math.random(PosZ - SizeZ, PosZ + SizeZ)
	local RayOrigin = Vector3.new(Position1, Region.Position.Y, Position2)
	local RayDirection = Vector3.new(0, -500, 0)
	local RaycastParamsData = RaycastParams.new()
	RaycastParamsData.FilterDescendantsInstances = {SpawnFolder}
	RaycastParamsData.FilterType = Enum.RaycastFilterType.Blacklist
	local RaycastResult = workspace:Raycast(RayOrigin, RayDirection, RaycastParamsData)
	if RaycastResult ~= nil then
		local Part = Instance.new("Part", SpawnFolder)
		Part.Position = RaycastResult.Position
		Part.Color = Color3.fromRGB(255, 0, 0)
		Part.Anchored = true
		Part.Name = "Object"
		Part.CanCollide = false

Any feedback or possible solutions are recommended / supported, however please make sure it’s something I can write and learn instead of using a simple module or something :eyes:

If possible I however want to spawn it 1.34 studs above the floor.

Probably has something to do with this:

Saving the initial position and not updating it when the part moved/has moved.

Just move it in the while loop with the Sizes.

1 Like

Sorry for the late reply, that did it thank you :slight_smile: