2013-10-20 58 views
0

我目前正在研究2D彈跳球物理學,它可以上下彈跳球。物理行爲正常,但最終速度保持+3,然後0不停,即使球已經停止反彈。我應該如何修改代碼來解決這個問題?彈跳球問題

這裏是視頻顯示它是如何工作的。 注意:Bandicam無法記錄-3和0之間的速度轉換。因此,當球停止彈跳時它只顯示-3。
https://www.youtube.com/watch?v=SEH5V6FBbYA&feature=youtu.be

這裏是生成的報告:https://www.dropbox.com/s/4dkt0sgmrgw8pqi/report.txt

ballPos   = D3DXVECTOR2(50, 100); 
    velocity  = 0; 
    acceleration = 3.0f; 
    isBallUp  = false; 

void GameClass::Update() 
{ 
    // v = u + at 
    velocity += acceleration; 

    // update ball position 
    ballPos.y += velocity; 

    // If the ball touches the ground 
    if (ballPos.y >= 590) 
    { 
     // Bounce the ball 
     ballPos.y = 590; 
     velocity *= -1; 
    } 

    // Graphics Rendering 
    m_Graphics.BeginFrame(); 
    ComposeFrame(); 
    m_Graphics.EndFrame(); 
} 

回答

0

當球停止彈跳時,放置一個isBounce標誌以使速度爲零。

void GameClass::Update() 
{ 
    if (isBounce) 
    { 
     // v = u + at 
     velocity += acceleration; 

     // update ball position 
     ballPos.y += velocity; 
    } 
    else 
    { 
     velocity = 0; 
    } 

    // If the ball touches the ground 
    if (ballPos.y >= 590) 
    { 
     if (isBounce) 
     { 
      // Bounce the ball 
      ballPos.y = 590; 
      velocity *= -1; 
     } 


     if (velocity == 0) 
     { 
      isBounce = false; 
     } 
} 
0

只有加快如果球不在地面上說謊:

if(ballPos.y < 590) 
    velocity += accelaration; 

順便說一句,你不應該在球的位置設爲590如果您檢測到碰撞。相反,將時間倒回到球擊中地面的時刻,反轉速度並快速向前退出時間。

if (ballPos.y >= 590) 
{ 
    auto time = (ballPos.y - 590)/velocity; 
    //turn back the time 
    ballPos.y = 590; 
    //ball hits the ground 
    velocity *= -1; 
    //fast forward the time 
    ballPos.y += velocity * time; 
} 
+0

你的代碼似乎不起作用。如果你沒有ballPos.y + =速度,ballPos.y怎麼能達到590? – user

+0

現在的問題是每次反彈都會遇到<= 3的情況。所以,當球停止彈跳時,我需要找到停止增加速度的方法。這裏是生成的報告:dropbox.com/s/4dkt0sgmrgw8pqi/report.txt – user

+0

當然,你做'ballPos.y + = velocity'。我剛剛提到了更改後的代碼部分。我們在談論什麼?<= 3?條件?畢竟,你怎麼阻止球?你還沒有發佈這個代碼,對吧?我會通過用'0到1之間的因子多重'velocity'來做到這一點。 –