Raycast returning nil while it shouldn't

I’m making a first person shooter combat system following a guide on this forum, I finished the guide and I’m continuing by experimenting with it and adding more stuff.

My issue: How the gun works is that it shoots a ray from the barrel to the mouse position, and it works. The problem is that it doesn’t always work. Sometimes the rig that I put get damaged, and sometimes not.

image

This should have damaged the rig, but it didn’t and the raycast is empty.

I’m not that advanced in scripting systems, but I thought it would be a good idea to increase the Z in the size of the ray so it maybe goes through the part and count it as a hit, but I got unexpected results.

-- Main script (local)
-- This shoots a ray like the image above, and then does some damage if it hits.

local target = game.Players.LocalPlayer:GetMouse().Hit.Position

MainModule.cast(Groza.Model.GunComponents.Barrel.Position, target, GunModel)
-- Module script (called by local script)

function module.cast(origin, endposition, ignored)
    local direction = endposition - origin
	local ray = Ray.new(origin, direction)
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = {ignored}
	params.FilterType = Enum.RaycastFilterType.Exclude
	local raycast = workspace:Raycast(ray.Origin, ray.Direction, params)
	local hitPosition = raycast and raycast.Position or origin + (endposition + Vector3.new(0, 0, 5)) * 1000
	
	local p = Instance.new("Part")
	p.Parent = workspace
	p.Anchored = true
	p.Color = Color3.new(1, 0, 0)
	p.CanCollide = false
	p.Size = Vector3.new(.1, .1, ray.Direction.Magnitude)
	p.CFrame = CFrame.lookAt(ray.Origin + ray.Direction / 2, ray.Origin)

    if raycast then
		print("raycast hit")
		if raycast.Instance.Parent:FindFirstChild("Humanoid") then
			-- do some damage
		end
	else
		print("raycast miss")
		print(raycast) -- this is the printed variable in the output in the above image (nil)
	end
end

Problem solved: I had to increase the size of the ray in case it didn’t fully reach the target, that means what I tried to solve the issue before posting this was correct, but just implemented incorrectly.

The correct implementation:

local raycast = workspace:Raycast(ray.Origin, ray.Direction * 1.5, params)

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