Need constructive feedback on my turrent handler

I need constructive feed back on the following:

Readability of code
Efficiency of code

( Thanks in advance )

local RunService = game:GetService("RunService")
local ServerStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")

local turrentsFolder = workspace.Turrents:GetChildren()

local function rotateObject(object, objectToLookAt)
	object.CFrame = CFrame.new(object.Position, objectToLookAt.Position)
end

local function createProjectile(bullet, anchored, canCollide, object, objectToLookAt ,bulletSpeed)
	
	local newProjectile = ServerStorage.Bullet:Clone()
	newProjectile.Anchored = anchored
	newProjectile.CanCollide = canCollide
	newProjectile.Position = object.Position
	
	rotateObject(newProjectile, objectToLookAt)
	
	newProjectile.Parent = workspace
	
	local newBodyVelocity = Instance.new("BodyVelocity")
	newBodyVelocity.Velocity = object.CFrame.LookVector.Unit * bulletSpeed
	newBodyVelocity.Parent = newProjectile
	
end

local function detectTarget(gun, targetValue)
	
	for _, player in ipairs(Players:GetPlayers()) do
		
		local character = player.Character or player.CharacterAdded:Wait()
		local humanoid = character:FindFirstChildWhichIsA("Humanoid")
		local hrp = character:FindFirstChild("HumanoidRootPart")
		
		if not targetValue.Value then
			if character and humanoid and hrp then
				if humanoid.Health > 10 then
				    targetValue.Value = humanoid					
				end
			end 
		else
			
			createProjectile(ServerStorage.Bullet, false, false, gun, hrp, 50)
			
			local connection
			connection = RunService.Heartbeat:Connect(function()
				
				if not targetValue.Value then
					connection:Disconnect()
				end
				
				rotateObject(gun, hrp)
			end)
			
			if humanoid.Health <= 0 then
				targetValue.Value = nil
			end
		end
	end
end

for _, turrent in ipairs(turrentsFolder) do
	if turrent then
		
		local gun = turrent.Main.Gun
		local targetValue = turrent.Main.Gun:FindFirstChild("Target")
		
		if not targetValue then
			warn("No object value Target found, expected 'Target'")
		else
			if not gun then
				warn("No part Gun found, expected 'Gun'")
			end
		end
		
		while wait(1) do
		    detectTarget(gun, targetValue)		
		end
		
	end
end

If you don’t want the turret to go down a bit you can set the cframe with .fromMatrix() instead

1 Like