按时间正确地进行模拟

时间:2013-10-14 20:05:59

标签: c simulation

我有一个小样本模拟,想到它就像把球抛向空中。我希望能够“加速”模拟,因此它将在更少的#循环中完成,但是“球”仍然会像在正常速度(1.0f)一样高。

现在,模拟以较少的迭代次数完成,但球的坐标太高或太低。这有什么不对?

static void Test()
{
    float scale = 2.0f;
    float mom = 100 * scale;
    float grav = 0.01f * scale;
    float pos = 0.0f;

    int i;
    for (i = 0; i < 10000; i++)
    {
        if (i == (int)(5000 / scale)) // Random sampling of a point in time
            printf("Pos is %f\n", pos);

        mom -= grav;
        pos += mom;
    }
}

1 个答案:

答案 0 :(得分:1)

'scale'是您尝试用来更改时间步长的变量吗?

如果是这样,它应该影响妈妈和pos的更新方式。所以你可以从替换

开始
mom -= grav;
pos += mom;

mom -= grav*scale;
pos += mom*scale;

也许这段伪代码有帮助..

const float timestep = 0.01; // this is how much time passes every iteration
                             // if it is too high, your simulation
                             // may be inaccurate! If it is too low, 
                             // your simulation will run unnecessarily
                             // slow!

float x=0; //this is a variable that changes over time during your sim.
float t=0.0; // this is the current time in your simulation

for(t=0;t<length_of_simulation;t+=timestep) {
    x += [[insert how x changes here]] * timestep;
}