在XNA中模拟重力

bat*_*man 5 c# xna game-physics xna-4.0

我试图通过引力在我的XNA 2D游戏中为2D精灵制作动画.我已经开发了一个非常基础的类来实现模拟效果.这是我的示例代码.

namespace Capture
{
class PhysX
{
    static Vector2 g = new Vector2(0.0f, 10.0f);
    public Vector2 pos, vel, acc, accumForce;
    public float mass;
    public bool USE_GRAVITY = true;

    /* Constructor */
    public void Engage(ref GameTime gameTime, uint maxX, uint maxY)
    {

        Vector2 F = Vector2.Zero;
        if (USE_GRAVITY)
        {
            F = accumForce + mass * g;
        }

        acc = F / mass;//This is the Net acceleration, Using Newtons 2nd Law
        vel += acc * gameTime.TotalGameTime.Seconds;// v = u + a*t
        pos += vel * gameTime.TotalGameTime.Seconds;// s = u*t + 0.5*a*t*t, 
        pos.X %= maxX;
        pos.Y %= maxY;

    }

    public void ApplyForce(ref Vector2 f)
    {
        accumForce += f;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我在PhysX#Engage()方法中调用Game#Update(GameTime gt)方法.问题是我没有得到一个平滑的动画.这是因为这个位置很快就会变得很大.为了克服我试图取模数,如在代码中显示Viewport.Width, Viewport.Height但仍然位置坐标一点也不平滑.我该怎么办.如何使动画流畅?请帮忙.

Hei*_*bug 3

我认为发生这种情况是因为您将经过的时间值视为整数。

尝试使用秒的双值,甚至考虑小数部分:

flaot dt = (float)GameTime.ElapsedGameTime.TotalSeconds;
vel += acc * dt;// v = u + a*t
pos += vel * dt;// s = u*t + 0.5*a*t*t,
Run Code Online (Sandbox Code Playgroud)

此外:

这是因为仓位很快就会变得非常大。

嗯,你应该保持浮点值尽可能接近 [-1,+1] 范围,否则你会失去精度。我的建议是:

  1. 将对象的浮动属性保持在较小的范围内([-1,+1])
  2. 根据您的分辨率在绘制之前转换您的值