Heal Gun raycasting result is nil

Hey! I’m trying to create a heal/medi gun. It detects the closest player to you, locks onto them and heals them as long as your mouse button is still down (As long as they are in the same team as you, aren’t dead and is not behind a wall.

Although, the raycast doesn’t seem to actually get any results half of the time, but on the other hand, it sometimes does but doesn’t actually get the player.

I can’t seem to find any solution, it could be something really simple that I’m missing but I cannot find the problem.

The player I’m testing with is also in the same team, they aren’t dead and they’re not behind a wall.

local gun = script.Parent
local buttonDown = false

-- CONFIG

local healRate = 0.2
local health = 10
local charge = script.Parent.Charge.Value
local range = 100

gun.Activated:Connect(function()
	buttonDown = true
	local player = game.Players:GetPlayerFromCharacter(script.Parent.Parent)
	local mag = nil
	local target = nil
	-- Locks on
	for i, v in pairs(game.Players:GetChildren()) do
		if v.Character:FindFirstChild("Humanoid") then
			local human = v.Character:FindFirstChild("Humanoid")
			local hrp = v.Character:FindFirstChild("HumanoidRootPart")

			if mag == nil or (gun.Handle.Position - hrp.Position).Magnitude < mag and (gun.Handle.Position - hrp.Position).Magnitude <= range and human.Health > 0 and v.Team == player.Team and v.Name ~= player.Name then
				local originPos = gun.Handle.Position
				local direction = (gun.Handle.Position - hrp.Position).Unit * range
				local rayParams = RaycastParams.new()
				rayParams.FilterDescendantsInstances = {script.Parent.Parent, gun.Handle}
				rayParams.FilterType = Enum.RaycastFilterType.Blacklist
				local rayResult = game.Workspace:Raycast(originPos, direction, rayParams)
				if rayResult then
					print(rayResult.Instance)
					if rayResult.Instance.Parent.Name == hrp.Parent.Name then
						mag = (gun.Handle.Position - hrp.Position).Magnitude
						target = hrp.Parent
					else
						print("Object in the way - " .. rayResult.Instance:GetFullName())
					end
				end
			end
		end
	end

	while wait(healRate) do
		if buttonDown and target ~= nil then
			print(target.Name)
			target.Humanoid.Health += health
		else
			break
		end
	end
end)

gun.Deactivated:Connect(function()
	buttonDown = false
end)

Thanks in advance!

1 Like

The direction is incorrect, it should be going to the hrp.Position then traveling from the gun handle position so (-gun.Handle.Position).

 hrp.Position - gun.Pos

It’s always a good idea to visualize the raycast as a part in order to debug something like this.

For the second one I’m not really sure try printing out your variables and seeing what its hitting and stuff.

Thanks! It seems to work perfectly now.