Raycast Inconsistencies and sometimes not hitting anything

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I want to create a raycast based off of the position given
  2. What is the issue? Include screenshots / videos if possible!
    the raycast only hits it’s target sometimes
function shot(plr,pos)
	local beam = script.Parent.otherstuff.effects.Beam:Clone()
	local particle = script.Parent.otherstuff.effects.ParticleEmitter:Clone()
	local barrel = game.Workspace:FindFirstChild(plr.Name)["Laser Gun"].Handle.Part
	local dir =  pos - barrel.Position 
	local rayParam = RaycastParams.new()
	rayParam.FilterDescendantsInstances = {workspace.LazerTagAssets, barrel.Parent.Parent, plr.Character}
	rayParam.FilterType = Enum.RaycastFilterType.Blacklist
	rayParam.CollisionGroup = "Default"
	rayParam.IgnoreWater = true
	local ray = workspace:Raycast(barrel.Position, dir, rayParam)
	print("remote")
	if ray then
		local hitins = ray.Instance
		local hitpos = ray.Position
		beam.Parent = barrel
		local hitatt = Instance.new("Attachment")
		hitatt.Parent = hitins
		hitatt.WorldPosition = hitpos
		beam.Attachment0 = barrel.Attachment
		beam.Attachment1 = hitatt
		particle.Parent = hitatt
		beam.Enabled = true
		particle.Enabled = true
		print("shot : " .. hitins.Name)
		wait(0.1)
		hitatt:Destroy()
		particle:Destroy()
		beam:Destroy()
	end
end

game.ReplicatedStorage.FireLaser.OnServerEvent:Connect(shot)

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

Try doing

rayParam.IgnoreWater = true
-	local ray = workspace:Raycast(barrel.Position, dir, rayParam)
+local ray = workspace:Raycast(barrel.Position, dir.Unit*1000, rayParam)
	print("remote")

The reason is because the direction stops at mouse position which is the surface of the part.

So to solve this we make the ray length a constant length of 1000 to make it pass through the mouse position and pierce the part

7 Likes