2013-10-20 89 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'来做到这一点。 –