c ++向量,指针等

时间:2013-03-16 15:10:57

标签: c++ pointers vector

我正在做一些基本的碰撞检测作业。我有一个包含一堆球体对象的向量,这些对象具有半径,位置,速度等成员。我已将我的问题缩小到以下代码。

这是我给出的代码有效。对于矢量球体中的每个球体,它会检查矢量球体中的所有其他球体是否发生碰撞。

// Do the physics simulation
for ( unsigned int i = 0; i < spheres.size(); i++ )
{   
    spheres[i].computeForces(gravity, air_friction, walls, spheres);
}

引用此函数:(最后一个参数是球体矢量)

// Compute all the forces between a sphere and the walls and other spheres and gravity and drag.
void computeForces(Vec3d gravity, double dragConstant, plane walls[6], std::vector< sphere > & spheres)
{
    clearForce();
    accumulateGravity( gravity );
    accumulateDrag( dragConstant );
    // Now check for collisions with the box walls
    for ( int j = 0; j < 6; j++ )
        accumulatePlaneContact(walls[j]);

    //Check for collisions with external spheres in the environment
    for ( unsigned int j = 0; j < spheres.size(); j++ )
        if ( this != &spheres[j] ) // Don't collide with yourself
            accumulateSphereContact( spheres[j] );
}

我修改了一些内容,以便我不必检查每个球体与其他球体,但只是一次比较一个,这不起作用。

// Do the physics simulation
for ( unsigned int i = 0; i < spheres.size(); i++ )
{
            //Here I can choose which spheres to test
    for (unsigned int j = 0; j < spheres.size(); j++)
    {
    spheres[i].computeForce(gravity, air_friction, walls, spheres[j]);
    }
}

使用此函数:(最后一个参数是单个球体)

void computeForce(Vec3d gravity, double dragConstant, plane walls[6], sphere & s)
{
    clearForce();
    accumulateGravity( gravity );
    accumulateDrag( dragConstant );
    for ( int j = 0; j < 6; j++ )
    {
        accumulatePlaneContact(walls[j]);
    }
    if (this != &s)
    {
        accumulateSphereContact(s);
    }
}

在调试模式下运行,它运行正常并且似乎正确地输入所有函数并进行计算,但它就像力实际上没有保存到球体对象中。我让球体相互穿过。 (与墙壁,重力和阻力的碰撞都可以正常工作)。

有什么区别?我的第一个猜测是它与它有关。我也尝试使用unordered_map而不是带有相同结果行为的vector。

1 个答案:

答案 0 :(得分:1)

请注意,在第一种情况下,computeForces()(包括对clearForce()的调用)仅在每个球体上调用一次。在您修改过的案例中,您为每个合作伙伴范围调用computeForce()一次,并且每个调用都clearForce()。我猜这就是问题所在。