#include "CS_PeEnergyCharge.h"

CS_PeEnergyCharge::CS_PeEnergyCharge(std::shared_ptr<Entity> parent, float lifeTime)
{
    type = 3;
    attackParent = parent;
    this->lifeTime = lifeTime;
    lifeTime_max = lifeTime;
    float dx = (float)Random(-10, 10);
    float dy = (float)Random(-10, 10);
    x = dx * lifeTime_max + parent->x;
    y = dy * lifeTime_max + parent->y;
    vx = -dx;
    vy = -dy;
    last_x = x;
    last_y = y;
    r = (float)Random(2, 8);
}

void CS_PeEnergyCharge::Step()
{
    auto wattackParent = attackParent.lock();
    if (wattackParent)
    {
        auto vec = XMVector2Normalize(XMVectorSet(wattackParent->x - x, wattackParent->y - y, 0, 0));
        auto vLen = sqrtf(vx * vx + vy * vy);
        vx = vLen * XMVectorGetX(vec);
        vy = vLen * XMVectorGetY(vec);
    }
    if (lifeTime > 0)
        lifeTime--;
    //没到时间但是已经在距离内
    if (wattackParent && DisappearDistance(wattackParent->x, wattackParent->y))
        Destroy();
    if (lifeTime <= 0)
    {
        if (wattackParent)
        {
            if (DisappearDistance(wattackParent->x, wattackParent->y))
                Destroy();
            else
            {
                vx *= 1.1f;
                vy *= 1.1f;
            }
        }
        else
            Destroy();
    }
    float alpha = (lifeTime_max - lifeTime) / (lifeTime_max);
    //设置图案
    AddFillFadeCircle(fillList, 0, r, 0, RGBA(0xf8, 0x4b, 0xff, alpha * 0xff));
    //执行运动
    Entity::Step();
}

bool CS_PeEnergyCharge::DisappearDistance(float dstX, float dstY)
{
    float dx = dstX - x;
    float dy = dstY - y;
    return dx * dx + dy * dy <= max(1.0f, vx * vx + vy * vy);
}

void SetCS_PeEnergyCharge(std::shared_ptr<Entity> parent, float lifeTime)
{
    auto pe = std::make_shared<CS_PeEnergyCharge>(parent, lifeTime);
    parent->gameFunc->SetEntity(parent, pe);
}
