My raycasts are failing and I don’t know why. I know they’re failing because RaycastResult is consistently nil, though it seems like I have the correct parameters here. I’m almost certain that the problem is the way I get the direction vector, but I can’t tell - it’s my first time using the new raycast method and despite it being clear that there’s no difference in the logic between these and the deprecated methods, it does seem different.
I cannot share all of production code but I can share the raycasting I’m doing. Below is test code that can be ran in StarterPlayerScripts. You will see that it will only work sometimes (when on the move or pointed at a certain angle), but at other times it refuses to cast at all despite being in an appropriate location. I need to have those casts all work.
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local LocalPlayer = Players.LocalPlayer
local PlayerMouse = LocalPlayer:GetMouse()
local MouseRaycastParams = RaycastParams.new()
local character
local humanoidRootPart
--- Cast a ray every frame
local function heartbeat()
local mouseHitPosition = PlayerMouse.Hit.Position
local mouseCastResults = workspace:Raycast(
humanoidRootPart.Position,
(mouseHitPosition - humanoidRootPart.Position),
MouseRaycastParams
)
print("CastResults:", mouseCastResults)
--- Create a ray visualiser
do
if not mouseCastResults then
print("Could not cast")
return
end
local distance = (mouseCastResults.Position - humanoidRootPart.Position).Magnitude
local line = Instance.new("Part")
line.BrickColor = BrickColor.new("Hot pink")
line.CastShadow = false
line.Material = Enum.Material.Neon
line.Transparency = 0.75
line.Name = "RayVisual"
line.Anchored = true
line.CanCollide = false
line.Size = Vector3.new(0.1, 0.1, distance)
line.CFrame = CFrame.new(mouseCastResults.Position, humanoidRootPart.Position) * CFrame.new(0, 0, -distance/2)
line.Parent = workspace
end
end
--- Handle character variables
local function characterAdded(newCharacter)
character = newCharacter
humanoidRootPart = newCharacter:WaitForChild("HumanoidRootPart")
MouseRaycastParams.FilterDescendantsInstances = {newCharacter}
end
LocalPlayer.CharacterAdded:Connect(characterAdded)
RunService.Heartbeat:Connect(heartbeat)
if LocalPlayer.Character then
characterAdded(LocalPlayer.Character)
end
Looking for substantiated, knowledgeable answers, not speculation. Thank you in advance.