首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单的AI移动算法不能正常工作

简单的AI移动算法不能正常工作
EN

Stack Overflow用户
提问于 2012-09-25 04:59:57
回答 1查看 859关注 0票数 1

我正在开发一个非常简单的移动算法,它接受D3DXVECTOR3的向量,并将AI移动到每个点。问题是,如果我超过一个点,AI似乎会卡在等于这些点的平均值的点上。

这些点是(x,z):

10,10

10,20

30,30

60,20

maxSpeed是10,只是为了测试。

代码语言:javascript
复制
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;
        }
    }
}

我只是在寻找一些关于如何让它工作的技巧。尽管这看起来是一个非常简单的问题,但我现在很困惑。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-25 06:38:52

代码语言:javascript
复制
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++;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12572842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档