c# – Xna将重力添加到2d精灵中

我试图在我的第一个xna 2d游戏中模拟引力.我有以下内容
//Used for Jumping
    double elapsedAirTime = 0.0;
    double maxAirTime = 8.35;
    //End Jumping

所以我试图将精灵向上移动一定量,而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;
            }
        }

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

解决方法

为了让你的精灵感受到引力,你应该为你的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;
}

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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...