Xna将重力添加到2d精灵

Azi*_*ziz 6 c# xna game-physics

我试图在我的第一个xna 2d游戏中模拟引力.我有以下内容

        //Used for Jumping
    double elapsedAirTime = 0.0;
    double maxAirTime = 8.35;
    //End Jumping
Run Code Online (Sandbox Code Playgroud)

所以我试图在elapsedAirTime <maxAirTime时将精灵向上移动一定量但是,有一些问题我的代码似乎只在这段时间内将精灵向上移动一次而不是多次.这是我的"player.cs"类中的代码,或者类的更新方法.

if (newState.IsKeyDown(Keys.Space))
        {
            if(oldState.IsKeyUp(Keys.Space))
            {
                //if we are standing or jumping then change the velocity
                if (playerState == PlayerStates.Standing)
                {
                    playerState = PlayerStates.Jumping;
                    this.position.Y -= (float)(30.0 + ((1.2)*elapsedAirTime)*elapsedAirTime);
                }
            }
        }
        //if we are jumping give it some time
        if (playerState == PlayerStates.Jumping)
        {
            if ((elapsedAirTime < maxAirTime) && position.Y < 3)
            {
                this.position.Y -= (float)(30.0 + ((1.2) * elapsedAirTime)*elapsedAirTime);
                elapsedAirTime += gameTime.ElapsedGameTime.TotalSeconds;
            }
            //otherwise time to fall
            else
            {
                playerState = PlayerStates.Falling;
            }

        }

        //add gravity to falling objects
        if (playerState == PlayerStates.Falling || playerState == PlayerStates.Standing)
        {
            //if we are above the ground
            if (this.position.Y < windowBot - 110)
            {
                //chnage state to falling
                playerState = PlayerStates.Falling;
                this.position.Y += 3.0f + ((float)(gameTime.ElapsedGameTime.TotalSeconds));
            }
            else
            {
                playerState = PlayerStates.Standing;
                elapsedAirTime = 0.0f;
            }
        }
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助,谢谢!

Dar*_*dro 11

为了让你的精灵感受到引力,你应该为你的Sprite类添加速度和加速度.然后,为Sprite创建一个Update方法,并在每次更新时将加速度添加到您的力度中,并将速度添加到每次更新的位置.位置不应基于经过的空气时间量.您可以将加速度设置为恒定的重力值,然后在跳跃时添加到Sprite的速度.这将创造一个看起来不错的流动抛物线跳跃.如果要包含计时,可以将GameTime传递给Sprite的Update方法,并将其用作速度的修饰符.这是一个示例Update方法:

void Update(GameTime gt)
{
    int updateTime = gt.ElapsedGameTime.TotalMilliseconds - oldgt.ElapsedGameTime.TotalMilliseconds;
    float timeScalar = updateTime / AVG_FRAME_TIME;
    this.velocity += this.acceleration * timeScalar;
    this.position += this.velocity;
    oldgt = gt;
}

void Update()
{
    this.velocity += this.acceleration;
    this.position += this.velocity;
}

我建议使用更简单的方法,直到你准确理解时序如何工作以及为什么需要实现它.

  • 使用 timeScalar 的原因是 a) 如果您想更改默认帧速率,或 b) 如果您的计算机速度太慢以至于无法跟上 XNA 尝试的默认 60 UPS/FPS。在任何一种情况下,如果您落后于目标更新率,您的游戏在没有 timeScalar 代码的情况下看起来会滞后。 (2认同)