#include "stdafx.h"
#include "LineOfSightIntercepting.h"
#include "DxWrapper.h"

const float LineOfSightIntercepting::TOLERANCE = 0.1f;       // tolerance range for the calculation of the target vector


LineOfSightIntercepting::LineOfSightIntercepting(void)
{
}


LineOfSightIntercepting::LineOfSightIntercepting(GameObject3D* pHostCraft, const GameObject3D& preyObject)
{
    m_pHostObject = pHostCraft;
    m_pPrey     = &preyObject;
}

LineOfSightIntercepting::~LineOfSightIntercepting(void)
{
}

void LineOfSightIntercepting::SetPreyObject(const GameObject3D& preyObject)
{
    m_pPrey = &preyObject;
}


void LineOfSightIntercepting::SetHostObject(GameObject3D* hostObject)
{
    m_pHostObject = hostObject;
}



void LineOfSightIntercepting::Cycle(float deltaMs)
{
    assert(m_pHostObject);

    if (m_pPrey)
    {
        // Erstmal die sogenannte "closing Velocity" berechnen, das ist die Differenz zwischen den Geschwindigkeitsvektoren von prey und predator.
        // Wird benutzt, um den ungefähren Zeitpunkt zu berechnen, wann der predator das ziel eingeholt hat.
        closingVelocityVector = m_pPrey->m_Velocity - m_pHostObject->m_Velocity;

        // der range-Vektor ist der Abstand zum Ziel
        range = m_pPrey->m_Position - m_pHostObject->m_Position;

        float timeToClose = range.magnitude() / closingVelocityVector.magnitude();    // die Zeit, wann das Ziel ungefähr erreicht ist

        predictedPosition = m_pPrey->m_Position + (m_pPrey->m_Velocity * timeToClose);

        targetVector =  predictedPosition - m_pHostObject->m_Position;
        targetVector.rotate2D(- m_pHostObject->m_RotZ);      
        targetVector.normalize();
       
        if(targetVector.x < - LineOfSightIntercepting::TOLERANCE)
        {
            this->m_pHostObject->m_RotZ -= m_pHostObject->m_RotationSpeed * deltaMs;
            //DxWrapper::Instance()->WriteLog();
        }
        else if (targetVector.x > LineOfSightIntercepting::TOLERANCE)
        {
            this->m_pHostObject->m_RotZ += m_pHostObject->m_RotationSpeed * deltaMs;
            //DxWrapper::Instance()->WriteLog("DoLineOfSightChase() ROTATE RIGHT");
        }         
    }
}

void LineOfSightIntercepting::Draw()
{

}