简单的AI运动算法无法正常工作

时间:2012-09-24 20:59:57

标签: c++ algorithm directx directx-9

我正在研究一个非常简单的移动算法,该算法接收D3DXVECTOR3 s的向量并将AI移动到每个点。问题是,如果我将其传递超过一个点,AI似乎会卡在与点数平均值相等的点上。

点是(x,z):
 10,10  10,20  30,30  60,20

maxSpeed仅用于测试。

void Obj::MoveToLocation(D3DXVECTOR3 newLocation, float deltaTime)
{
    D3DXVECTOR3 directionToTarget = newLocation - location;
    D3DXVec3Normalize(&directionToTarget, &directionToTarget);

    location += maxSpeed * directionToTarget * deltaTime;   
}

void Obj::Patrol(std::vector<D3DXVECTOR3> locations, float deltaTime)
{
    hasArrived = false;

    for (int i = 0; i < locations.size(); ++i)
    {
        if (!hasArrived)
            MoveToLocation(locations[i], deltaTime);

        if ((location.x <= locations[i].x + radius.x) && (location.x >= locations[i].x - radius.x) &&
            (location.z <= locations[i].z + radius.z) && (location.z >= locations[i].z - radius.z))
        {
            hasArrived = true;
        }
    }
}

我只是在寻找一些有关如何使其正常工作的提示。我现在感到很茫然,尽管这似乎是一个非常简单的问题。

1 个答案:

答案 0 :(得分:0)

void Obj::MoveToLocation(D3DXVECTOR3 newLocation, float deltaTime)
{
    D3DXVECTOR3 directionToTarget = newLocation - location;

    if (D3DXVec3Length(&directionToTarget) <= maxSpeed * deltaTime)
    {
        // If this step would take us past the destination, just stop there
        // instead.
        location = newLocation;
    }
    else
    {
        D3DXVec3Normalize(&directionToTarget, &directionToTarget);

        location += maxSpeed * directionToTarget * deltaTime;   
    }
}

// Call this once to set the patrol route
void Obj::Patrol(std::vector<D3DXVECTOR3> locations)
{
    patrolRoute = locations;
    patrolIndex = 0; // Maybe pick the closest point instead?
}

// Call this each time the object should move (once per frame/turn)
void Obj::UpdatePatrol(float deltaTime)
{
    if (patrolRoute == NULL || patrolRoute.empty())
    {
        return;
    }

    if (patrolIndex >= patrolRoute.size())
    {
        // Start again from the beginning
        patrolIndex -= patrolRoute.size();
    }

    // Move towards the next location
    D3DXVECTOR3 nextLocation = patrolRoute[patrolIndex];
    MoveToLocation(nextLocation, deltaTime);

    float dx = location.x - nextLocation.x;
    float dz = location.z - nextLocation.z;

    if ((dx <= radius.x) && (dx >= -radius.x) &&
        (dz <= radius.z) && (dz >= -radius.z))
    {
        // We have reached it. Select the next destionation.
        patrolIndex++;
    }
}