BadGuy = Entity:createSubClass();

function BadGuy:init()
   self:setTexture("shmup1.tga");
   self:setGravityInfluence(0);
   self:setSpriteFrame(0, 160, 32, 192);
   self:setForceUpdate(true);
   self:setBlockable(true);

   self.angle = 45;
   self.speed = 10;

   self.shotCooldown = 0;

   local myShadow = Shadow:create();
   myShadow:assign(self);
   
end

function BadGuy:update()

   local x, y = self:getPos();

   local convertedAngle = (self.angle + 90) * 3.14159/180.0;

   local dx = math.cos(convertedAngle);
   local dy = math.sin(convertedAngle);

   if not (mainPlayer == nil) and not (mainPlayer:getDead()) then

	  local playerDeltaX, playerDeltaY = mainPlayer:getPos();

	  playerDeltaX = playerDeltaX - x;
	  playerDeltaY = playerDeltaY - y;

	  local dist = math.sqrt(playerDeltaX * playerDeltaX + playerDeltaY * playerDeltaY);

	  if (dist > 10) then

		 --self.angle = (math.acos(playerDeltaY / playerDeltaX)) * 180.0 / 3.14159;

		 --writeConsole(playerDeltaY.."\n");

		 local dot = playerDeltaX * dx + playerDeltaY * dy;
		 local cross = -1 * playerDeltaY * dx + playerDeltaX * dy;

		 local retreat = false;

		 if dot > 0 then
			
			-- Player is in front of us.

		 else

			-- Player is behind us.
			if dist < 200 then
			   retreat = true;
			end
			
		 end

		 local turnDelta = 0;
		 local turnSpeed = 2;

		 if cross > 0 then

			-- Player is to the right.
			if retreat then
			   turnDelta = 1;
			else
			   turnDelta = -1;
			end

		 elseif cross < 0 then
			
			-- Player is to the left.
			if retreat then
			   turnDelta = -1;
			else
			   turnDelta = 1;
			end

		 end

		 if cross == 0 then

			-- Player is directly in front or behind.
			turnDelta = 0;

		 end

		 self.angle = self.angle + turnDelta * turnSpeed;


		 if self.shotCooldown <= 0 then

			if retreat then
			else
			   -- Shoot at the player.
			   
			   local shotSpeed = 5;
			   local shotOffset = 32;

			   local newShot = BadShot:create();
               newShot:setLayer(3);

			   newShot:setSpriteAngle(self.angle);

			   x = x + dx;
			   y = y + dy;
			   newShot:setPos(x + dx * shotOffset, y + dy * shotOffset);

			   newShot:setVel(dx * (shotSpeed + self.speed), dy * (shotSpeed + self.speed));

			   self.shotCooldown = 20;
			   
			end

		 else

			self.shotCooldown = self.shotCooldown - 1;

		 end

	  end

   end

   self:setVel(dx * self.speed, dy * self.speed);

   self:setSpriteAngle(self.angle);

   baddieCount = baddieCount + 1;

end

function BadGuy:collided(otherEnt)
   
   local x,y = self:getPos();
   local ent = entitiesByName[otherEnt];
   
   if not (ent == nil) then

	  if ent.isPlayerShot then
		 
		 addSplosion(x, y).subsplosions = 2;

		 self:die();
		 ent:die();

		 playerScore = playerScore + 1;
		 writeConsole("Score: "..playerScore.."\n");
	  end

   end

end

registerSpawn("BadGuy");

