Help with Raycasting gun

  1. What do you want to achieve?
    I need help with my gun.

  2. What is the issue?
    I create a raycast but whenever I shoot, the raycast stops at the gun.

  3. What solutions have you tried so far?
    I printed what the raycast touches and it came out that it touches the gun. Then I filtered out the object: “RayCastParams.FilterDescendantsInstances = {player.Character, handle}”. However, this did not help either. I then tried to create the raycast a little further in front so that it doesn’t touch the weapon at all. To do this, I added another block (FocusPart1). But now the raycast stops at the other block (FocusPart2).

Local Script
	local gun = script.Parent
	local handle = script.Parent:FindFirstChild("Handle")
	local focusPart1 = handle:WaitForChild("FocusPart1")
	local focusPart2 = handle:WaitForChild("FocusPart2")
	local player = game:GetService("Players").LocalPlayer
	local RayCastParams = RaycastParams.new()
	RayCastParams.FilterType = Enum.RaycastFilterType.Exclude
	RayCastParams.FilterDescendantsInstances = {player.Character, focusPart1, focusPart2} 

	local UIS = game:GetService("UserInputService")
	UIS.InputBegan:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			local rayCast = Ray.new(focusPart1.Position + Vector3.new(), focusPart2.Position - focusPart1.Position)
			local hitPart, hitPosition = game.Workspace:FindPartOnRay(rayCast)
			local rayDistance = (hitPosition - focusPart1.Position).Magnitude
			local MidPoint = focusPart1.Position + (hitPosition - focusPart1.Position)/2

			if hitPart then
				print(hitPart)
				local Bullet = Instance.new("Part")
				Bullet.CFrame = CFrame.new(MidPoint, hitPosition)
				Bullet.Parent = game.Workspace
				Bullet.Material = Enum.Material.Neon
				Bullet.BrickColor = BrickColor.new("New Yeller")
				Bullet.Anchored = true
				Bullet.CanCollide = false
				Bullet.CanQuery = false
				Bullet.Transparency = 0.4
				Bullet.Size = Vector3.new(0.1,0.1, rayDistance)

				task.wait(0.1)

				Bullet:Destroy()
			end
		end
	end)

Video:

Is there anything I did wrong and if so, how can I fix it?

2 Likes

i’m not sure why you’re using raycastparams, which is meant for the newer version of raycasting, for the older version. you aren’t passing the raycastparams in any functions therefore nothing is being excluded.

1 Like

And do you know how I can fix my problem then? Is there any new way?

1 Like

you can still use the old version of raycasting and use the :FindPartOnRayWithIgnoreList method though it’s deprecated so consider switching to the new method of raycasting

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