RayCast being inconsistent

I’m trying to get familiar with raycasts and projectiles and during my testing I found that my raycast would sometimes result in nil even if I would be hovering over an instance as you can see here

I’m not sure if this is something on my end or if its something I can fix, but here’s my code

local plr = game.Players.LocalPlayer
local char = script.Parent
local hum = char:WaitForChild("Humanoid")
local humRP = char:WaitForChild("HumanoidRootPart")

local RS = game:GetService("ReplicatedStorage")
local Debris = game:GetService("Debris")
local UIS = game:GetService("UserInputService")


local debounce = false
local CD = 0

local tpRemote = RS.Remotes.Teleport

local mouse = plr:GetMouse()

local KEY = Enum.KeyCode.V

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {char}


local function throwKunai()
	
	local kunai = RS.FX.RaijinKunai:Clone()
	
	local rayOrigin = humRP.Position
	local rayDirection = mouse.Hit.Position

	local raycastResult = game.Workspace:Raycast(rayOrigin, rayDirection - rayOrigin, raycastParams)
	
	if raycastResult == nil then print("nil")
		return
	end
	
	local objHit = raycastResult.Instance
	
	local spawnPart = Instance.new("Part")
	spawnPart.Position = raycastResult.Position
	spawnPart.Material = objHit.Material
	spawnPart.BrickColor = objHit.BrickColor
	spawnPart.Parent = workspace.Map.Ignore
	
	print(objHit)
	print("Pressed V")
	
end

UIS.InputBegan:Connect(function(inp, gpe)
	if gpe then return end
	if inp.KeyCode == KEY and not debounce then
		debounce = true
		throwKunai()
		tpRemote:FireServer(mouse.Hit.Position)
		task.wait(CD)
		debounce = false
	end
end)


It looks like the problem here is that you are casting the ray from the humanoid root position when that is not where mouse.hit casts its ray from (so the direction of the ray would mismatch the length traveled resulting in the ray falling short). Instead, I think using camera:ViewportToRay() would be better suited for this situation (it casts a ray from the camera):

local camera = workspace.CurrentCamera
local rayMaxDistance = [[INSERT THE MAXIMUM DISTANCE YOU WANT YOUR RAY TO DETECT AN OBJECT HERE]]
local mousePosition = UserInputService:GetMouseLocation()
local rayInformation = camera:ViewportPointToRay(mousePosition.X, mousePosition.Y)
local raycastResult  = workspace:Raycast(rayInformation.Origin, rayInformation.Direction * rayMaxDistance)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.