#include "CS_FallRock.h"
#include "CS_PeSmoke.h"
CS_FallRock::CS_FallRock()
{
	type = 2;
	ani.png = L"CS_CaveStoryMod";
	cbRect.enableCbRect = true;
	cbRect.enableSoild = false;
	cbRect.left = cbRect.right = cbRect.top = cbRect.bottom = 8;
	damage_reset_counter = 60;
	attackState_reset_counter_max = 60;
	speedDir = true;
	isTrap = true;
}

void CS_FallRock::Step()
{
	//入水水花效果
	if (cbRect.inWater)
	{
		if (setSplash)
		{
			//产生水花
			auto nE = gameFunc->GameCreateEntity(L"pe_splash");
			nE->x = x;
			nE->y = y;
			//岩浆红
			if (cbRect.inLava)
				nE->color = RGBA(0xff, 0, 0, 0xff);
			gameFunc->SetEntity(shared_from_this(), nE);
			setSplash = false;
		}
		//水中
		vy += 0x20 / ts;
		if (vy > 0x380 / ts)
			vy = 0x380 / ts;
	}
	else
	{
		setSplash = true;
		//空中
		vy += 0x40 / ts;
		if (vy > 0x700 / ts)
			vy = 0x700 / ts;
	}
	if (sleepState_counter > 0)
		sleepState_counter--;
	if (sleepState_counter == 0 &&
		!(cbRect.cbLeft || cbRect.cbRight || cbRect.cbTop || cbRect.cbBottom))
	{
		//完全离开墙壁，才可以参与坠击
		bFallState = true;
		cbRect.enableSoild = true;
	}
	if (cbRect.cbBottom && bFallState)
	{
		bFallState = false;
		cbRect.enableSoild = false;
		if (cbRect.inWater)
			sleepState_counter = sleepState_counter_max * 2;
		else
			sleepState_counter = sleepState_counter_max;
		vy = -0x200 / ts;
		gameFunc->PlaySound(L"CS_026_quake");
		if (gameFunc->SetQuake)
			gameFunc->SetQuake(gameFunc->game, 10, 0);
		//产生烟雾
		for (int i = 0; i < 4; ++i)
		{
			auto pe = std::make_shared<CS_PeSmoke>();
			pe->x = x + Random(-12, 12);
			pe->y = y + 0x2000 / ts;
			pe->vx = Random(-341, 341) / ts;
			pe->vy = Random(-0x600, 0) / ts;
			gameFunc->SetEntity(shared_from_this(), pe);
		}
	}
	//超出地图销毁
	int mapW = 0, mapH = 0;
	gameFunc->GetMapSize(gameFunc->mapSizeGetter, &mapW, &mapH);
	if (y > ((mapH + 2) * 16))
	{
		Destroy();
		return;
	}
	//清除最后一次碰撞结果
	Entity::ClearCollisionResult();
	//执行运动
	Entity::Step();
	//执行碰撞
	Entity::Collision();
}

void CS_FallRock::SetState(int stateID, int lr)
{
	ani.sprite_index = el.arg;
}

void CS_FallRock::Attack(std::weak_ptr<Entity> dst, int* outDamage, float* outAngle, bool* outTakedown, int* outElemType, float* outShockForce, float* outHeavy)
{
	auto wdst = dst.lock();
	if (wdst)
	{
		if (wdst->y > y)
		{
			*outDamage = 10;
			if (wdst->lr == 0)
			{
				*outAngle = 315;
			}
			else
			{
				*outAngle = 225;
			}
			*outTakedown = true;
			*outElemType = 0;
			*outShockForce = 0x200 / ts;
			*outHeavy = 2;
		}
	}
}

std::shared_ptr<Entity> CreateCS_FallRock()
{
	return std::make_shared<CS_FallRock>();
}
