xna更新方法 - 为什么=符号表现为+ =

时间:2011-04-24 11:10:11

标签: xna

这是关于射弹类更新方法的代码。 每个fram将previousXposition添加到最后一个结果,而不是替换最后一个结果。 这个问题的原因和解决方案是什么?

public void Update(GameTime gameTime)
{

    if (Position.X != previousXPosition)
    {
        flightTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
        Position.X += previousXPosition;
        Position.Y -= previousYPosition;

        previousXPosition = (projectileVelocity.X * flightTime) + 0.5f * (wind * (float)Math.Pow(flightTime, 2));
        previousYPosition = (projectileVelocity.X * flightTime) + 0.5f * (gravity * (float)Math.Pow(flightTime, 2));
     }

1 个答案:

答案 0 :(得分:0)

以这种方式累积'flightTime'并不适合速度变化。它假定整个飞行的速度的每一帧都是这个特定的框架,而事实并非如此。

这是我建议编写弹丸飞行编码的方法。将“速度”建立为矢量2,其方向代表射弹的行进方向,其大小代表其行进的每秒单位速度。

    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; // time since last frame only

    // the velocity vector will have a magnitude equiv to units traveled per second.
    float speed = velocity.Length();
    Vector2 windDrag = (Vector2.Negate(velocity) / speed) * (speed * speed * dragCOef);
    Vector2 gravity = Vector2.UnitY * gravCOef;// gravity can be a constant per unit time.

    Vector2 velocityChange = windDrag + gravity;
    velocity += velocityChange * elapsed;// adds just the change of velocity this frame to the overall velocity
    Position += velocity * elapsed;// 'velocity' is distance traveled per second. 'velocity * elapsed' is just distance traveled per frame

0