向量值变为NaN

时间:2018-12-05 00:24:39

标签: c++

由于程序中的各种浮点数和向量分量,我一直得到nan(不是数字)。我几乎100%确信与碰撞有关,因为在弄乱碰撞代码之前这从来都不是问题。

即使在调试时,幅值方法中的总和也显示为NaN,这使我相信一个向量在传递给函数之前就在中断,但我找不到它是哪个。

以下是我认为与问题相关的方法

void Simplex::PhysicsInfo::Collision(PhysicsInfo info)
{
    vector3 oldVel = velocity;
    if (magnitude(oldVel) == 0.0f)
    {
        return;
    }
    vector3 nextVelDirect = glm::normalize(info.position - position);

//make all ball to ball collisions elastic

    float angle = acosf(glm::dot(oldVel, nextVelDirect)
            / (magnitude(glm::normalize(oldVel)) * magnitude(nextVelDirect)));
    angle = sinf(angle);
    if (angle < 0)
        angle *= -1;
    float nextVecMag;
    if (magnitude(info.velocity) == 0 && angle != 1)
    {
        //This next line is not correct, use if actual line isn't working and you absolutely need something
        //info.velocity = 0.5f * oldVel.length * nextVelDirect;

        //actual line
        info.velocity = angle * magnitude(oldVel) * nextVelDirect;
        vector3 nextVec = (magnitude(oldVel) * oldVel)
                - (magnitude(info.velocity) * info.velocity);
        nextVecMag = magnitude(nextVec);
        if (nextVecMag < 0)
        {
            nextVecMag *= -1;
        }
        nextVecMag = sqrt(nextVecMag);
        velocity = nextVecMag * glm::normalize(nextVec);
    }
    else if (magnitude(info.velocity) == 0)
    {
        info.velocity = oldVel;
        velocity = vector3(0.0f);
    }
    if (isnan(velocity.x) || isnan(velocity.y) || isnan(velocity.z))
    {
        std::cout << "-" << std::endl;
    }
}

PhysicsInfo::PhysicsInfo(float mss, vector3 pos, vector3 cent, vector3 limit)
{
    velocity = vector3(0.1f);
    acceleration = vector3(0.0f);
    mass = mss;
    position = pos;
    center = cent;
    limits = limit;
    frictionMagnitude = 0.005f;
}
vector3 PhysicsInfo::normalize(const vector3 &v)
{
    float sum = (v.x * v.x) + (v.y * v.y) + (v.z * v.z);
    if (sum < 0)
    {
        sum *= -1;
    }
    float length_of_v = sqrt(sum);
    return vector3(v.x / length_of_v, v.y / length_of_v, v.z / length_of_v);
}

float PhysicsInfo::magnitude(const vector3 &v)
{
    float sum = (v.x * v.x) + (v.y * v.y) + (v.z * v.z);
    if (sum < 0)
    {
        sum *= -1;
    }
    float length_of_v = sqrt(sum);
    if (isnan(length_of_v))
    {
        throw ExceptionCollidedUnwind;
    }
    return length_of_v;
}

很抱歉格式化。我不习惯在这里发布。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我还没有解决问题,但是我已经知道原因是Collision方法中acosf()函数的参数。点方法有时返回超出[-1,1]的必需范围,即acosf()方法的参数的必需浮点范围。这是因为我在得到点积之前没有对两个向量进行归一化。