【问题标题】:Bouncing ball issue弹跳球问题
【发布时间】:2013-10-28 19:19:54
【问题描述】:

我目前正在研究上下弹跳球的 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();
}

【问题讨论】:

    标签: c++ directx physics game-physics


    【解决方案1】:

    设置一个 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;
            }
    }
    

    【讨论】:

      【解决方案2】:

      只有在球不落地时才加速:

      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;
      }
      

      【讨论】:

      • 您的代码似乎不起作用。如果没有ballPos.y += velocity,ballPos.y怎么能达到590?
      • 现在的问题是每次反弹都会满足
      • 当然是ballPos.y += velocity。我刚刚提到了更改的代码部分。我们在谈论什么&lt;= 3 条件?你到底是怎么停球的?您还没有发布此代码,对吧?我会通过将 velocity 乘以 0 到 1 之间的因子来做到这一点。
      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 2013-01-13
      • 2013-05-23
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多