
NPC = Actor:createSubClass();
registerSpawn("NPC");

totalNPCs = 0;

function NPC:init()

   Actor.init(self);

   self:setColor(255, 0, 0);

   totalNPCs = totalNPCs + 1;

   self.jumpCooldown = 0;

   self.flowDirection = (math.random() - 0.5) * 2;

   self.isNPC = true;

end

function NPC:destruct()

   totalNPCs = totalNPCs - 1;

end

function NPC:gotHit(vx, vy)
   
   local bonus = BonusEgg:create();
   
   local x, y = self:getPos();
   local dx, dy = self:getVel();

   --bonus:setPos(x - vx, y - vy);
   bonus:setPos(x, y);
   --bonus:setVel(dx - vx, dy - vy);
   bonus:setVel(dx, dy);

   self:die();

end

function NPC:update()

   Actor.update(self);

   local npcJumpBoost = 8;
   local jumpCooldownTime = 4;
   local lookRadius = 128;
   local randomJumpProbability = 0.07;

   local npcAccel = 0.25;
   local npcMaxSpeed = 4;
   local npcMaxVertSpeed = 8;

   local avoidanceFactor = 2;

   local x, y = self:getPos();
   local dx, dy = self:getVel();

   local nearEnts = getEntsTouchingBox(
      self:getLayer(),
      x - lookRadius,
      y + lookRadius,
      x + lookRadius,
      y - lookRadius);

   local shouldBoost = false;

   local avoidance = 0;

   -- If we're below any nearby players, try to get above them!
   for k, v in pairs(nearEnts) do
      
      local ent = entitiesByName[v];
      
      if ent.isPlayer then
         
         local px, py = ent:getPos();
         
         -- Get above the player, but not if the player is already way
         -- above us.
         if (py > y) and (py - y < 64) then
            shouldBoost = true;
         end

      end

      if ent.isNPC then

         -- Avoid other NPCs.
         
         local px, py = ent:getPos();

         if x > px then
            avoidance = avoidance + 1;
         end

         if x < px then
            avoidance = avoidance - 1;
         end

      end

   end

   if math.random() < randomJumpProbability then
      shouldBoost = true;
   end


   -- Avoid falling to death.
   if y < screenBottom + 128 then
      
      if getBoxTouchesWorld(self:getLayer(), x - 2, y, x + 2, y - 256) then

         -- Okay, we're still above ground.

      else

         -- Jump, or we'll fall off the bottom.
         shouldBoost = true;

      end

   end

   
   if shouldBoost and self.jumpCooldown <= 0 then
      self:startFlapAnim();
      dy = dy + npcJumpBoost;
      self.jumpCooldown = jumpCooldownTime;
   else
      self.jumpCooldown = self.jumpCooldown - 1;
   end

   dx = dx + npcAccel * self.flowDirection + avoidance * avoidanceFactor;

   if dx > npcMaxSpeed then
      dx = npcMaxSpeed;
   end

   if dx < -npcMaxSpeed then
      dx = -npcMaxSpeed;
   end

   if dy > npcMaxVertSpeed then
      dy = npcMaxVertSpeed;
   end

   if dy < -npcMaxVertSpeed then
      dy = -npcMaxVertSpeed;
   end

   self:setVel(dx, dy);

end


