#include "PeRainDrip.h"
#include "PeSpark.h"
PeRainDrip::PeRainDrip()
{
	type = 3;
	angle = 90;
	length = (float)Random(25, 50);//25-50
	speed = 0x400 / ts;
	vx = speed * cosf(angle * deg2rad);
	vy = speed * sinf(angle * deg2rad);
	//启用碰撞
	cbRect.enableCbRect = true;
	cbRect.enableSoild = true;
	SetShape();
}

void PeRainDrip::Step()
{
	for (int i = 0; i < 4; i++)
	{
		//执行运动
		Entity::Step();
		//清除最后一次碰撞结果
		Entity::ClearCollisionResult();
		//执行碰撞
		Entity::Collision();
		//雨的颜色随房间颜色
		color = cbRect.roomColor;
		SetShape();
		//在碰到地面后播放浪花动画
		if (!bSpray && (cbRect.cbBottom || cbRect.cbLeft || cbRect.cbRight || cbRect.inWater))
		{
			bSpray = true;
			vx = 0;
			vy = 0;
			SetPeSparkSmall(shared_from_this(), x, y, 2, 5, 270);
		}
		//消失
		if (bSpray)
		{
			length -= speed;
			if (length < 0)
				Destroy();
		}
		if (x < -50)
			Destroy();
		//其他消失
		auto wrain = rain.lock();
		if (wrain)
		{
			if (y > wrain->y)
				Destroy();
		}
		else
		{
			if (exist > 0)
			{
				exist--;
				if (exist == 0)
					Destroy();
			}
		}
	}
}

void PeRainDrip::DeltaTime(float deltaTime)
{
	//绘制位置
	if (lineList.size() < lineList_set_last.size())
		lineList.resize(lineList_set_last.size());
	for (int i = 0; i < lineList_set_last.size(); i++)
	{
		auto& dst = lineList[i];
		auto& src_last = lineList_set_last[i];
		auto& src = lineList_set[i];
		dst.x = lerp(src_last.x, src.x, deltaTime);
		dst.y = lerp(src_last.y, src.y, deltaTime);
		dst.c = src.c;
	}
	Entity::DeltaTime(deltaTime);
}

void PeRainDrip::SetState(int stateID, int lr)
{
	this->lr = lr;
	if (lr == 0)
	{
		angle = 100;
	}
	else
	{
		angle = 80;
	}
	vx = speed * cosf(angle * deg2rad);
	vy = speed * sinf(angle * deg2rad);
	SetShape();
}

void PeRainDrip::SetShape()
{
	lineList_set_last.swap(lineList_set);
	float x1 = 0;
	float y1 = 0;
	float x2 = length * cosf((angle + 180) * deg2rad);
	float y2 = length * sinf((angle + 180) * deg2rad);
	AddLine(lineList_set, 0, x1, y1, color, x2, y2, color);
	cbRect.left = cbRect.right = cbRect.top = 8;
	cbRect.bottom = 0;
}

std::shared_ptr<Entity> CreatePeRainDrip()
{
	return std::make_shared<PeRainDrip>();
}
