I made a turret script, and I have no idea why it won't work. No errors, I can't print either, I've tried rewriting this script numerous times but nothing worked.
local GunM = script.Parent.Parent:WaitForChild("Gun",2)
local Gun = GunM:FindFirstChild("Barrel")
Range = 10
--Range (In studs) it can target
Damage = 10
--Power of the gun
ShotDelay = 1
--Delay between shots
Color = Vector3.new(255,0,0)
--Color of the beam
Transp = 0.5
--Transparency of the beam
Mat = "Neon"
--Material of the beam
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = Range
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("Torso")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
function shootAtNearest()
local near = findNearestTorso(Gun.Position)
local ray = Ray.new(Gun.CFrame.p, (near.Position - Gun.Position).unit * 300)
local part, position = workspace:FindPartOnRay(ray, Gun, false, true)
local beam = Instance.new("Part", workspace)
beam.Color = Color
beam.FormFactor = "Custom"
beam.Material = Mat
beam.Transparency = Transp
beam.Anchored = true
beam.Locked = true
beam.CanCollide = false
local distance = (Gun.Position - position).magnitude
beam.Size = Vector3.new(Damage/20, Damage/20, distance)
beam.CFrame = CFrame.new(Gun.Position, position) * CFrame.new(0, 0, -distance / 2)
game:GetService("Debris"):AddItem(beam, 0.1)
local ehum = part.Parent:findFirstChild("Humanoid") or part.Parent.Parent:findFirstChild("Humanoid")
if ehum ~= nil then
ehum:TakeDamage(Damage)
end
end
while true do
local t = findNearestTorso(Gun.Position)
if t then
Gun.CFrame = CFrame.new(Gun.Position,t.Position)
shootAtNearest()
end
wait(ShotDelay)
end
I tried replacing while true do with a clickdetector event just to test if it's working without that, but nothing happened.
