c# – Xna将重力添加到2d精灵中
发布时间:2020-12-15 06:27:51 所属栏目:百科 来源:网络整理
导读:我试图在我的第一个xna 2d游戏中模拟引力.我有以下内容 //Used for Jumping double elapsedAirTime = 0.0; double maxAirTime = 8.35; //End Jumping 所以我试图将精灵向上移动一定量,而elapsedAirTime maxAirTime 但是,有一些问题,我的代码似乎只在这段时间
我试图在我的第一个xna 2d游戏中模拟引力.我有以下内容
//Used for Jumping double elapsedAirTime = 0.0; double maxAirTime = 8.35; //End Jumping 所以我试图将精灵向上移动一定量,而elapsedAirTime< maxAirTime 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; } 我建议使用更简单的方法,直到你准确理解时序如何工作以及为什么需要实现它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |