Raycast.Position returning nil when pointed at nothing

This is the script im using

local function beforeCamera(delta)
	if holding == true then
		local player = game:GetService("Players").LocalPlayer
		local mouse = player:GetMouse()
		local castParams = RaycastParams.new()
		castParams.FilterDescendantsInstances = {game.Workspace.Baseplate , game.Workspace.SubAreas }
		castParams.FilterType = Enum.RaycastFilterType.Whitelist
		local ray = workspace:Raycast(mouse.UnitRay.Origin, (mouse.Hit.p - mouse.UnitRay.Origin).unit * 5000 , castParams)

		local pos = ray.Position
		
		script.Parent:WaitForChild("Humanoid"):MoveTo(pos)
	else
		script.Parent:WaitForChild("Humanoid"):MoveTo( game.Players.LocalPlayer.Character.HumanoidRootPart.Position )

	end
end

RunService:BindToRenderStep("Before camera", 100, beforeCamera)

My problem is that if you point the mouse at the skybox, position is nil, despite this not being the case with mouse.hit.p, how can i make the skybox be valid?


Here’s the documentation for mouse hit:

Mouse | Roblox Creator Documentation
The mouse’s internal ray extends for 1000 studs. If the mouse is not pointing at an object in 3D space (for example when pointing at the sky), this property will be 1000 studs away from the Workspace.CurrentCamera .


Documentation for Raycast:

WorldRoot | Roblox Creator Documentation
Note that the length (magnitude) of the directional vector is important, as objects/terrain further away than its length will not be tested.
RaycastResult Contains the results of a raycast operation, or nil if no eligible BasePart or Terrain cell was hit.

So if you wanted you could make a fake invisable sky with a script like this

local Rando = Random.new()

local max = Vector2.new(2048*100,2048*100)
local size = Vector3.new(2048,0.05,2048)
local y = workspace.FallenPartsDestroyHeight + 1

local plate = Instance.new("Part")
plate.Anchored = true
plate.CastShadow = false
--plate.TopSurface = Enum.SurfaceType.Studs
plate.Massless = true
plate.CanCollide = false
plate.CanTouch = false
plate.Size = size

local function spnplate(x,z)
	local clone :Part = plate:Clone()
	clone.Color = Color3.new(Rando:NextNumber(),Rando:NextNumber(),Rando:NextNumber())
	clone.Position = Vector3.new(x,y,z)
	clone.Parent = workspace
end

print("Spawning:",math.floor((max.X/size.X) * (max.Y/size.Z)),"baseplates")
for x=0,max.X,size.X do 
	wait()
	for z=0,max.Y,size.Z do 
		spnplate(x,z)
		spnplate(-x,-z)
		spnplate(x,-z)
		spnplate(-x,z)
	end
end 
1 Like