【问题标题】:Calculating velocity using consistent speed in basic C++ engine在基本 C++ 引擎中使用一致的速度计算速度
【发布时间】:2019-01-18 21:47:19
【问题描述】:

我想要实现的是一个精灵在 2D 环境中移动到另一个精灵。我从基本的 Mx = Ax - Bx 交易开始。但我注意到精灵越接近目标,它的速度就越慢。因此,我尝试根据速度创建一个百分比/比率,然后每个 x 和 y 都获得了速度津贴的百分比,但是,它的行为非常奇怪,并且似乎只有在 Mx 和 My 为正时才有效 以下是代码摘录:

ballX = ball->GetX();
    ballY = ball->GetY();
    targX = target->GetX();
    targY = target->GetY();
    ballVx = (targX - ballX);
    ballVy = (targY - ballY);
    percentComp = (100 / (ballVx + ballVy));
    ballVx = (ballVx * percentComp)/10000;
    ballVy = (ballVy * percentComp)/10000;

/10000 是为了减缓精灵的移动

【问题讨论】:

  • 您可以使用勾股定理将ballV的长度设置为特定数字。
  • “我从基本的 Mx = Ax - Bx 交易开始。但我注意到精灵越接近目标,它的速度就越慢。”听起来您的输入或输出首先有问题您需要调试而不是调整公式来解决您的错误。您应该找到第二个点的向量,并按增量时间缩放该向量以找到新位置。

标签: c++ game-physics velocity


【解决方案1】:

假设您希望精灵以恒定速度移动,您可以在 X 和 Y 位置上进行线性淡入淡出,如下所示:

#include <stdio.h>

int main(int, char **)
{
   float startX = 10.0f, startY = 20.0f;
   float endX = 35.0f, endY = -2.5f;
   int numSteps = 20;

   for (int i=0; i<numSteps; i++)
   {
      float percentDone = ((float)i)/(numSteps-1);
      float curX = (startX*(1.0f-percentDone)) + (endX*percentDone);
      float curY = (startY*(1.0f-percentDone)) + (endY*percentDone);

      printf("Step %i:  percentDone=%f curX=%f curY=%f\n", i, percentDone, curX, curY);
   }
   return 0;
}

【讨论】:

    【解决方案2】:

    感谢您的回复,我现在可以正常工作了,但是标准化了向量而不是整个百分比,这就是我现在所拥有的:

        ballX = ball->GetX();
        ballY = ball->GetY();
        targX = target->GetX();
        targY = target->GetY();
        ballVx = (targX - ballX);
        ballVy = (targY - ballY);
        vectLength = sqrt((ballVx*ballVx) + (ballVy*ballVy));
        ballVx = (ballVx / vectLength)/10;
        ballVy = (ballVy / vectLength)/10;  
    

    【讨论】:

    • 当球在目标上时注意除以零(如果你还没有检查过)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多