【问题标题】:Simulating gravity in XNA在 XNA 中模拟重力
【发布时间】:2011-12-25 06:33:58
【问题描述】:

我正在尝试通过重力在我的 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;
    }
}
}

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

【问题讨论】:

  • 你的质量是多少?质量越大,加速度越慢。
  • @SteveH 力中的质量项和质量除法抵消了。重力加速度不依赖于质量。
  • @Anurag 您的速度随时间线性增加。通常你会引入一个速度线性的减慢项来模拟摩擦并限制终端速度。
  • 我不明白 maxX 和 maxY 的用途。你能给我解释一下吗?他们用什么样的值调用?

标签: c# xna xna-4.0 game-physics


【解决方案1】:

我认为这是因为您将经过的时间值作为整数。

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

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

另外:

这是因为仓位很快变大了。

嗯,你应该让浮点值尽可能地接近 [-1,+1] 范围,否则你会得到一个松散的精度。 我的建议是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    相关资源
    最近更新 更多