Raycast not working

Im trying to make atm a very simple gun. However, the code prints everytime it gets fired “nothing”, so the ray isnt detecting anything.
ServerScript:

event.OnServerEvent:Connect(function(plr, mousePos)
	local origin = plr.Character.Gun.Muzzle.Position
	local direction = mousePos.Position
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = {workspace.Baseplate, plr.Character}
	
	local result = workspace:Raycast(origin, direction, params)
	if result then
		print(result.Instance)
	else
		print("nothing")
	end
end)
1 Like

This looks like the issue. If mousePos is a CFrame, do:

local direction = mousePos.CFrame.LookVector * 4

because this means it will cast the way the mouse is pointing. You may need to multiply more than 4 times, it depends how far you want the ray to consider hits.

2 Likes

Yeap that works, but its like super weird how it prints. Its like printing HRT when Im not even hovering over it. There also has to be an issue with the origin and direction
EDIT: It only prints my char and not the dummy or Baseplate (I excluded the filter line)

It’ll only work right when the bullet originates from the mouse with the method they have provided. What needs to happen is that the bullet needs to be aimed at where the mouse is hovering over, which can be done like this:

local direction = mousePos.Position - origin

In fact, you can calculate the direction vector of any ray like this:

local direction = targetPosition - startPosition

You said you excluded the filter line, if you’ve removed any of the lines that modify the RaycastParams can you send them? The issue might be to do with those. Try what @Judgy_Oreo said too.

So this is what I get when I constantly aim at the baseplate without any changes
image

Script that I have now with mousePos being the mouse.Hit.Position:

event.OnServerEvent:Connect(function(plr, mousePos)
	local origin = plr.Character.Gun.Muzzle.Position
	local direction = mousePos - origin
	local params = RaycastParams.new()
	--params.FilterDescendantsInstances = {workspace.Baseplate, plr.Character}
	
	local result = workspace:Raycast(origin, direction, params)
	if result then
		print(result.Instance)
	else
		print("nothing")
	end
end)

Personally, I tend to have more success using this method to calculate the direction (mousePos will need to be the mouse.Hit.Position):

event.OnServerEvent:Connect(function(plr, mousePos)
	local origin = plr.Character.Gun.Muzzle.Position
	local direction = CFrame.lookAt(origin, mousePos).LookVector * 1000 -- 1000 is the ray's length
	local params = RaycastParams.new()
	--params.FilterDescendantsInstances = {workspace.Baseplate, plr.Character}
	
	local result = workspace:Raycast(origin, direction, params)
	if result then
		print(result.Instance)
	else
		print("nothing")
	end
end)
1 Like

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