I'm making a gun turret to practice my raycasting abilities, and I am following a tutorial, but I have a problem. A few, actually. First, and biggest, in the findTarget function the script generates a ray, and multiplies it by 500 with a .Unit . What does that do? Second, I want to use that ray to make sure that its not firing at a wall the humanoid is hiding behind, but instead, the humanoid itself. Third, how would I add inaccuracy to my gun? Fourth, the FireBullet() function works, but how do I make the sound sound like its overlapping, it doesn't sound right, its sounds glitchy. Heres the code:
gun = script.Parent function FindTarget() local dist = 100 local target = nil for i,v in pairs(workspace:GetChildren()) do local torso = v:FindFirstChild("Torso") local humanoid = v:FindFirstChild("Humanoid") if torso and humanoid and humanoid.Health > 0 then if (gun.Position - torso.Position).magnitude < dist then local ray = Ray.new(gun.Position, (gun.Position- torso.Position).Unit*500) local hit,position = workspace:FindPartOnRayWithIgnoreList(ray,{torso.Parent}) if hit == nil then dist = (gun.Position - torso.Position).magnitude target = torso else print(hit.Name) end dist = (gun.Position - torso.Position) target = torso end end end return target end function FireBullet() s = workspace.Sound:Clone() s.Parent = script.Parent s:Play() wait(0.6) s:Destroy() end while wait(0.3) do local torso = FindTarget() if torso then gun.CFrame = CFrame.new(gun.Position, torso.Position) local b = Instance.new("Part",workspace) b.Size = Vector3.new(0.2,0.2,1) b.BrickColor = BrickColor.new("New Yeller") b.Velocity = gun.CFrame.lookVector*500 b.CFrame = gun.CFrame + Vector3.new(0.2,0.2,0.2) b.Touched:connect(function(obj) FireBullet() local human = obj.Parent:FindFirstChild("Humanoid") if human then human:TakeDamage(5) end if obj ~= gun then game:GetService("Debris"):AddItem(b,0) end end) end end
I believe your problem is..
.~~~~~~~~~~~~~~~~~ for i,v in pairs(workspace:GetChildren()) do
I believe its this because not everything in the workspace may have a child 'Humanoid' which will trigger an error that will discontinue the code. You can use a pcall function or make it simple... But it will only work on Players
for i, v in pairs(game.Players:GetPlayers()) do wait() local Character = v.Character end
Another reason it may be breaking when player character code runs the player isn't fully loaded...
for i,v in pairs(workspace:GetChildren()) do wait() --Code end
~~~~~~~~~~~~~~~~~