function autoturret.init()

 local gun_barrel = load_particle("autoturret_gun_barrel.obj")

 local flare = load_particle("autoturret_flare.obj")
 local flare_glow = load_particle("autoturret_glow.obj")
 local bullet = load_particle("autoturret_bullet.obj")

 local movespeed = 2

 function autoturret.gun(worm)
  local angle = worm:data().autoturret_angle
  local dangle = worm:data().autoturret_dangle
  if not angle then
   angle = worm:angle()
  end
  local target = worm:closest_worm()
  local target_angle
  if target then
   local x1, y1 = worm:pos()
   local x2, y2 = target:pos()
   target_angle = (vector_direction(x1, y1, x2, y2) + 360)
  else
   target_angle = worm:angle() 
  end
  local difference_angle = (angle - target_angle) % 360
  if difference_angle > 180 then
   dangle = movespeed
  else
   dangle = -movespeed
  end
  angle = angle + dangle
  worm:data().autoturret_dangle = dangle
  worm:data().autoturret_angle = angle % 360

  local correction_angle = worm:angle()
  local flip = 1
  if correction_angle > 180 then
   correction_angle = 360-correction_angle
   flip = -1
  end

  worm:shoot(gun_barrel, 1, 2, 0, 0, 0, 0, flip * angle - correction_angle, 1)
  
 end
 function autoturret.shoot(worm)
  local angle = worm:data().autoturret_angle

  local correction_angle = worm:angle()
  local flip = 1
  if correction_angle > 180 then
   correction_angle = 360-correction_angle
   flip = -1
  end

  worm:shoot(bullet, 1, 1, 0, 0, 0, 0, flip * angle - correction_angle, 5)
  worm:shoot(flare, 1, 1, 0, 0, 0, 0, flip * angle - correction_angle, 5)
  

 end

 function autoturret.flare(object)
  local time = object:data().time
  if time then
   object:data().time = time + 0.4
  else
   object:data().time = 1.2
   time = 0
  end
  object:shoot(flare_glow, 4, 0.1, 0.1, 0, 0, 360, 0, 0.05*math.random(0,30)*math.sin(time))
 end



 function autoturret.casebounce(object)
  local x, y = object:spd()
  if x^2 + y^2 < 0.05 then
   object:set_angle(90)
   object:set_spd(0,0)
  end
 end


end
