2013-03-16 122 views
1

我正在做一些基本的碰撞檢測作業。我有一個向量,其中包含一些球體對象,其中包含半徑,位置,速度等成員。我已將範圍縮小到以下代碼。C++向量,指針等

這是我得到的代碼。對於矢量球中的每個球體,它會檢查矢量球中的所有其他球體是否存在碰撞。

// 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而不是具有相同結果行爲的向量。

+0

你在for循環中製作了一個新的球體矢量嗎? – 2013-03-16 15:13:48

+0

沒有。只有一個向量球體。 – kballing 2013-03-16 15:15:42

+0

只是對你的C++編碼的一般評論。這是缺乏的,它會導致你的責任。像這樣的事情,即使你知道它只被擊中一次,如果在for循環中每次迭代都付出代價。還有幾個C++的問題,但我提到的是最具體的問題。 – user805547 2013-03-16 15:23:44

回答

1

請注意,在第一種情況下,computeForces()(其中包括致電clearForce())在每個球體上僅被調用一次。在您修改的案例中,您要爲每個合作伙伴範圍調用computeForce()一次,並且這些調用中的每一個都是clearForce()。我想這就是問題所在。

+0

賓果。踢自己的那一個。 – kballing 2013-03-16 15:17:04

+0

@kballing如果解決了問題,您可能需要將答案標記爲已接受。 – Angew 2013-03-16 15:28:06

+0

我不得不等待8分鐘。 – kballing 2013-03-16 15:29:58