#include "CS_AmChainBat.h"
#include "CS_PeSmoke.h"

CS_AmChainBat::CS_AmChainBat(std::shared_ptr<Entity> target)
{
	type = 2;
	this->target = target;
	lr = x > target->x ? 0 : 1;
	//启用碰撞
	cbRect.enableCbRect = true;
	cbRect.enableSoild = true;
	cbRect.left = cbRect.right = 4;
	cbRect.top = 7;
	cbRect.bottom = 8;
	cbRect.waterBlock = true;
	cbRect.ignoreMovePlatform = true;
	attackState = false;
	//设置动画
	ani.png = L"CS_CaveStoryMod";
	ani.sprite_index = lr == 0 ? L"am_chainbat_fly_l" : L"am_chainbat_fly_r";
}

void CS_AmChainBat::Init(std::weak_ptr<Entity> self)
{
	stateGravity.Init(shared_from_this());
	Entity::Init(self);
}

void CS_AmChainBat::SetState(std::wstring stateName, int lr)
{
	if (stateName == L"release")
		ReleasTarget();
}

void CS_AmChainBat::Step()
{
	//清除最后一次碰撞结果
	Entity::ClearCollisionResult();
	//执行运动
	Entity::Step();
	//执行碰撞
	Entity::Collision();
	//捕获玩家
	auto wtarget = target.lock();
	if (wtarget)
	{
		if (bBind)
		{
			//目标无法移动或跳跃
			wtarget->vx = 0;
			wtarget->vy = 0;
			wtarget->x = x;
			wtarget->last_x = last_x;
			if (wtarget->y < y)
			{
				wtarget->y = y;
				wtarget->last_y = last_y;
			}
			//掉落到地上
			if (x > 39 * 16.0f)
				vx = -0x450 / ts;
			else if (x < 38.5f * 16.0f)
				vx = 0x450 / ts;
			else
				vx = 0;
			stateGravity.Step();
			ani.sprite_index = lr == 0 ? L"am_chainbat_chainbind_l" : L"am_chainbat_chainbind_r";
		}
		else
		{
			if (abs(x - wtarget->x) <= 4 && abs(y - wtarget->y) <= 4)
			{
				//锁住玩家到中心
				bBind = true;
				vx = wtarget->vx;
				vy = wtarget->vy;
			}
			//追击玩家
			const float speed = 0x450 / ts;
			lr = vx > 0 ? 1 : 0;
			float vec_x = wtarget->x - x;
			float vec_y = wtarget->y - y;
			auto vec = XMVector2Normalize(XMVectorSet(vec_x, vec_y, 0, 0));
			float dir_vx = XMVectorGetX(vec);
			float dir_vy = XMVectorGetY(vec);
			vx = dir_vx * speed;
			vy = dir_vy * speed;
			ani.sprite_index = lr == 0 ? L"am_chainbat_fly_l" : L"am_chainbat_fly_r";
		}
	}
	else
	{
		gameFunc->PlaySound(L"CS_070_expl_small");
		//创建云团
		SetCS_PeSmokeSmall(shared_from_this(), x, y);
		Destroy();
	}
}

void CS_AmChainBat::ReleasTarget()
{
	gameFunc->PlaySound(L"CS_070_expl_small");
	//创建云团
	SetCS_PeSmokeSmall(shared_from_this(), x, y);
	Destroy();
}
