Loading

XNA 跳跃简单算法和代码

刚一个朋友问跳跃怎么实现,其实对xna我也不了解,Zzk里搜索“XNA 跳跃”居然没有符合的记录,惊讶之余也有点冲动要不自己也搞一个?不过xna真的是不懂啊,找了两三个源码,笔者实在笨,没能理解它的算法实在见笑了。干脆自己动手从头实现一个,先从现实考虑起跳要考虑的因素是起跳速度(v1)体重(w)重力g然后根据物理xxx记不得了,咱不好高骛远了,simple is perfect 直接上代码:

全局参数:

        private bool _isJumping;
        private bool _jumpKeyDown;
        private float _jumpHeight = 100f;
        private TimeSpan _jumpTimeSpan = TimeSpan.FromMilliseconds(500);
        private double _jumpStartTime;
        private float _jumpStartPosition;

 Update中的代码:

_jumpKeyDown = Keyboard.GetState().IsKeyDown(Keys.Space);
            squarePosition.Y = DoJump(squarePosition.Y, gameTime);

 高度算法函数:

        private float DoJump(float velocityY, GameTime gameTime)
        {
            if (_jumpKeyDown && !_isJumping)
            {
                _isJumping = true;
                _jumpStartTime = gameTime.TotalGameTime.TotalMilliseconds;
                _jumpStartPosition = velocityY;
            }
            if (_isJumping)
            {
                var jumpTime = gameTime.TotalGameTime.TotalMilliseconds - _jumpStartTime;
                var topTime = _jumpTimeSpan.TotalMilliseconds / 2;
                if (jumpTime < _jumpTimeSpan.TotalMilliseconds)
                {
                    if (jumpTime > topTime)
                    {
                        velocityY =
                            _jumpStartPosition-_jumpHeight - Convert(-(jumpTime - topTime) * _jumpHeight / (_jumpTimeSpan.TotalMilliseconds - topTime));
                    }
                    else
                    {
                        velocityY =_jumpStartPosition+ Convert(-( jumpTime)*_jumpHeight/topTime);
                    }
                }
                else
                {
                    _isJumping = false;
                    velocityY = _jumpStartPosition;
                }

            }
            return velocityY;
        }

 

 

 

posted @ 2012-06-03 22:25  today4king  阅读(641)  评论(0编辑  收藏  举报