代码之家  ›  专栏  ›  技术社区  ›  user1054922

按时间适当缩放模拟

  •  1
  • user1054922  · 技术社区  · 12 年前

    我有一个小样本模拟,把它想象成把球扔到空中。我希望能够“加速”模拟,这样它将在更少的循环中完成,但“球”在空中的高度仍然与正常速度(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 回复  |  直到 12 年前
        1
  •  1
  •   weemattisnot    12 年前

    “scale”是您试图用来更改时间步长的变量吗?

    如果是这样的话,这应该会影响mom和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;
    }