Raycast always equals to nil

-- This is in a local script btw.
local hit, position = workspace:Raycast(plr.Character.chest.Position, mouse.Hit.Position)

if hit ~= nil then
       print(hit.Instance.Name)
else
      print("object is nil")
    end
end
local hit, position = workspace:Raycast(plr.Character.chest.Position, mouse.Hit.Position*500)

try this

1 Like

Its possible that the direction of the ray is too short

2 Likes
-- Will this work?
local hit, position = workspace:Raycast(plr.Character.chest.Position, mouse.Hit.Position*math.huge)

There’s a limit to how long the raycast is I believe its 15000 also putting it to a big number will most likely cause performance issues

You should be subtracting something from the mouse’s position in order to get a directional vector.

I wouldn’t do that. The longer the ray, the more it lags. Standard is around 500, but less is better.

1 Like

It still prints out “object is nil”.

Can you explain this in better detail?

plr.Character.chest.Position

Is chest a valid instance? Are you using custom rigs?

The second parameter of raycast is not the target, but the direction of the ray.

You can calculate the direction using
Mouse.Hit.Position - plr.Character.chest.Position

Also, if you don’t need to add extra paremeters to the raycast or extra results then you can just use the mouse’s properties that already have the Hit, Target and Surface

Chest is a valid instance. I’m using a custom skinned mesh character.

Thank you! I’m going to try this out soon and update you on how it goes.

It works perfectly. Thank you!

Technically the second parameter is the direction multiplied by some magnitude (which represents the ray’s distance).

Worked locally. Started glitching out when serversided.

-- It rarely detects anything.
workspace.Remotes.Shoot.OnServerEvent:Connect(function(plr, gunpos)
	local RayCastFilter1 = RaycastParams.new()
	RayCastFilter1.FilterType = Enum.RaycastFilterType.Blacklist;
	RayCastFilter1.FilterDescendantsInstances = {workspace[plr.Name]};
	local hit, position = workspace:Raycast(workspace[plr.Name].chest.Position, gunpos - workspace[plr.Name].chest.Position, RayCastFilter1)
	if hit then
		print(hit.Instance.Name)
	else
		print("fail")
	end
end)
local plr = game.Players.LocalPlayer

local mouse = plr:GetMouse()

mouse.Button1Up:Connect(function()
	workspace.Remotes.Shoot:FireServer(Vector3.new(mouse.Hit.Position))
end)

is there something I am missing here? I thought workspace:Raycast returned a RaycastResult object, where you can do RaycastResult.Position, RaycastResult.Instance, etc

Remove the Vector3.new(), the Hit.Position is already a Vector3