Raycast is not working properly

  1. Im making a gun that don’t hit the player, and his accessories, using raycasts.

  2. For some reason, raycast doesn’t see Dummy sometimes.

  3. I was looking for a solution on the forum, but I didn’t find anything.

I have a tool, that fires an event with origin position, and mouse position within it. It works, but sometimes in output window appears message that there was no hit even if my mouse is right on dummy. Please help me figure out what went wrong.

This is server script:

local RS = game:GetService("ReplicatedStorage")
local fire = RS:WaitForChild("fire")
local minDistance = script:FindFirstChild("minDistance").Value
local maxDistance = script:FindFirstChild("maxDistance").Value

fire.OnServerEvent:Connect(function(player, tool, fromPos, toPos)

	local rayParams = RaycastParams.new()
	rayParams.FilterType = Enum.RaycastFilterType.Blacklist
	rayParams.FilterDescendantsInstances = {player.Character}
	rayParams.IgnoreWater = true

	if (toPos-fromPos).magnitude < maxDistance and (toPos-fromPos).magnitude > minDistance then
		local newRay = game.Workspace:Raycast(fromPos,(toPos - fromPos),  rayParams, maxDistance)
		if newRay then			
			print("Hit:", newRay.Instance.Parent.Name.."'s "..newRay.Instance.Name)
		else
			warn("Something is on the way...?") --This SHOULDN'T appear, because only player's character is blacklisted.
		end
	else
		print("Too far or too close.")
	end
end)

This is local script:

local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local torso = char:WaitForChild("UpperTorso")
local tool = script.Parent
local mouse = player:GetMouse()

tool.Equipped:Connect(function(rifle)
	rifle.Button1Down:Connect(function()
		local fromPos = torso.Position
		local toPos = yourMouse.Hit.Position
		fire:FireServer(fromPos, toPos)
	end)	
end)


2 Likes

Solved.
Changed

game.Workspace:Raycast(fromPos,(toPos - fromPos),  rayParams, maxDistance)

to

game.Workspace:Raycast(fromPos,(toPos - fromPos).Unit*maxDistance, rayParams)
2 Likes