Turret not working. but there are no errors?

Hello everyone! I am trying to make a tower defense game named “turret shot” and i cant seem to get the turret working

The Code

local rep = game:GetService("ReplicatedStorage")
local bullet = rep:WaitForChild("bullet")

local turret = script.Parent

local firerate = 2
local bulletdamage = 5
local bulletspeed = 400
local aggrodist = 200

while wait(firerate) do
	
	local target = nil
	for i, v in pairs(game.Workspace.Folder:GetChildren()) do
		local hum = v:FindFirstChild("Humanoid")
		local torso = v:WaitForChild("Torso")
		if hum and torso and hum.Health > 0 then
			if (torso.Position - turret.Position).magnitude < aggrodist then
				ray = Ray.new(turret.Position, (torso.Position - turret.Position).Unit * aggrodist)
				local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(ray, {turret})
				
				if hit == torso then
					target = torso
				end
			end
		end
	end
	
	if target then
		local torso = target
		
		turret.CFrame = CFrame.new(turret.Position, torso.Position)
		
		local new = bullet:Clone()
		new.Position = turret.Position
		new.Parent = game.Workspace
		
		new.Velocity = turret.CFrame.LookVector * bulletspeed
		
		new.Touched:Connect(function(objectHit)
			local human = objectHit.Parent:FindFirstChild("Humanoid")
			if human then
				human:TakeDamage(bulletdamage)
			else
				wait(5)
				new:Destroy()
			end
		end)
	end
end

The script has no errors but it doesnt seem to work.

If any of you have feedback please send it!
thanks, Icy

Are you exactly sure that the targets are within the range of the turret?

This looks like it should work. Are your enemies in workspace.Folder? Also, make sure that the ray isn’t hitting parts on the enemy model other than its torso.

I don’t see anything wrong with the code but I would add print statements after each major step to see how far the code is getting.

i tried when i was running it to put it right next to the bots. still didnt work

there is suppose to be one enemy in the folder. then the replicated storage clones the enemies every 3 seconds into the workspace.Folder.

I suggest using Raycast since Ray is deprecated, then blacklist the turret model.

1 Like

I’d also suggest detecting all parts on the enemy model with the raycast to make sure that isn’t interfering, but maybe you had a reason that it has to be the torso in mind.

2 Likes

apparently when i look at the console it seems like they are not ranged. it works now! Thanks!

1 Like