I am trying to find an empty location around a player for another player to spawn at. Someone suggested raycasting and so that is what I am using. The code works fine when there are no parts around the player. The problem comes when there are some parts. I have a ceiling and two walls I put up to see if my code worked. When I stood under the ceiling and two walls and tried to get the other player to teleport to me, it did not work. So I put some prints in to see where the problem was and apparently my raycasting is detecting parts in all directions even the directions where there are none. Here is the script:
local function findEmptyDirection(character)
local hRPart = character:FindFirstChild("HumanoidRootPart")
if hRPart then
local xYOrZ
local offset
for i = 1, 5 do
if i == 1 then
xYOrZ = Vector3.new(0, 10, 0)
offset = Vector3.new(0, 7, 0)
elseif i == 2 then
xYOrZ = Vector3.new(8, 0, 0)
offset = Vector3.new(5, 0, 0)
elseif i == 3 then
xYOrZ = Vector3.new(-8, 0, 0)
offset = Vector3.new(-5, 0, 0)
elseif i == 4 then
xYOrZ = Vector3.new(0, 0, 8)
offset = Vector3.new(0, 0, 5)
elseif i == 5 then
xYOrZ = Vector3.new(0, 0, -8)
offset = Vector3.new(0, 0, -5)
end
local ray = Ray.new(hRPart.Position, hRPart.Position + xYOrZ)
local part, hitPosition = workspace:FindPartOnRay(ray, character)
if not part then
return hRPart.Position + offset
else
print(part.Name) -- this prints 5 times even though there should be only three parts
end
end
return false
end
end
Thanks!

1 comment
Thank you so much!