新旧位置之间的速度

时间:2018-12-04 13:46:52

标签: c++ math vector velocity

我在这里看到一些东西,它通过将旧pos保存为UNITY来加快速度,并提供一些代码:

void TestVelocity(Vector3& Pos, Vector3 &Result)
{
    Vector3 PreviousPos;

    if (GetTickCount() >= velupd)
    {
        velupd = GetTickCount() + 100//random timer for test;

        Vector3 Diff = Pos - PreviousPos;
        float Len = sqrtf(Diff .x * Diff .x + Diff .y * Diff .y + Diff .z * Diff .z);

        if (Len >= 0.01)
        {
            Result = (Diff / Len);
        }
    }
      PreviousPos = Pos.
}

计算错误。数据仅适用于对象位置(无速度等)。

1 个答案:

答案 0 :(得分:1)

需要更多详细信息才能为您提供更准确的答案。但是我基本上看到两个问题。您没有初始化 PreviousPos 对象,在我看来您希望它持久存在,对吧?

假设 Vector3 类具有负(-)运算符重载,那么您可以执行此操作,您可以这样做。

void TestVelocity(Vector3& Pos, Vector3 &Result)
{  
static Vector3 PreviousPos; //Initialize here the initial position to zero with your constructor

    if (GetTickCount() >= velupd)
    {
        velupd = GetTickCount() + 100//random timer for test;

        Vector3 Diff = Pos - PreviousPos;
        float Len = sqrtf(Diff .x * Diff .x + Diff .y * Diff .y + Diff .z * Diff .z);

        if (Len >= 0.01)
        {
            Result = (Diff / Len);
        }
    }
  PreviousPos = Pos.
}

另一种解决方案是将前一个位置作为参数,但是正如我所说,很难说我们是否不知道您想要的实现是什么。这些是建议,具体取决于所需的内容。