local attack_range = {}
local fire_delay = {}
local damage = {}
local fire_delay_init = {}
local turn_speed = {}
local angle_found = {}
local angle = {}

function heturret_init(e)
--set default values for all turrets (these will be overwritten if individual settings are set)
attack_range[e] = 1000
fire_delay[e] = 3000
fire_delay_init[e] = fire_delay[e]
damage[e] = 30
turn_speed[e] = 1
--do not change as it's required to find the starting angle
angle_found[e] = -1
angle[e] = 0

--set individual settings here
--eg
--damage[2] = 200
--damage[300] = 5000
end

function heturret_main(e)
--find entity starting angle so we can compare with players later (this is done by rotating turret to face the player on load)
--note this may cause problems if you wish your turret to stay a certain facing but i wouldn't recommend this script if so, sorry)
if angle_found[e] < 0 then
local x = g_PlayerPosX - g_Entity[e]['x']
local z = g_PlayerPosZ - g_Entity[e]['z']
angle[e] = math.atan2(x,z)
angle[e] = angle[e] * (180.0 / math.pi)
if angle[e] < 0 then
angle[e] = 360 + angle[e]
elseif angle[e] > 360 then
angle[e] = angle[e] - 360
end
CollisionOff(e)
SetRotation(e,0,angle[e],0)
angle_found[e] = angle[e]
end


--check player enters turrets sensor range
if GetPlayerDistance(e) <= attack_range[e] then
--find the angle required to face the player
x = g_PlayerPosX - g_Entity[e]['x']
z = g_PlayerPosZ - g_Entity[e]['z']
angle[e] = math.atan2(x,z)
angle[e] = angle[e] * (180.0 / math.pi)
if angle[e] < 0 then
angle[e] = 360 + angle[e]
elseif angle[e] > 360 then
angle[e] = angle[e] - 360
end
--compare angle to face player with our turret's current angle and update as needed
if angle_found[e] < angle[e] then
angle_found[e] = angle_found[e] + turn_speed[e]
elseif angle_found [e]> angle[e] then
angle_found[e] = angle_found[e] - turn_speed[e]
end

--keep angle within 0 ~ 360
if angle_found[e] > 360 then
angle_found[e] = 0
end

--update the new angle to be closer to player's position
SetRotation(e,0,angle_found[e],0)

--if we are facing the player
if angle[e] >= angle_found[e] - 1 and angle[e] <= angle_found[e] + 1 then
--if haven't fired lately then fire! :)
if GetTimer(e) >= fire_delay[e] then
PlaySound(e,1)
HurtPlayer(e,damage[e])
fire_delay[e] = GetTimer(e) + fire_delay_init[e]
end
end

--if player not in sensor range then rotate so we arent static
--remove this if you wish v
else
angle_found[e] = angle_found[e] + turn_speed[e]

if angle_found[e] > 360 then
angle_found[e] = 0
end

SetRotation(e,0,angle_found[e],0)
--end of removal of optional rotations ^
end
end