微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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;
}

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

原文地址:https://www.jb51.cc/csharp/95509.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐