How to slow down or stop key presses in XNA

后端 未结 12 2124
北恋
北恋 2021-02-01 05:38

I\'ve begun writing a game using XNA Framework and have hit some simple problem I do not know how to solve correctly.

I\'m displaying a menu using Texture2D and using th

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 05:56

    I know this is old, but how about: Add a threadsafe dictionary:

    private ConcurrentDictionary _keyBounceDict = new ConcurrentDictionary();
    

    Then use this method to track the keys pressed and determine if there is a key bounce:

            ///////////////////////////////////////////////////////////////////////////////////////////
        /// IsNotKeyBounce - determines if a key is bouncing and therefore not valid within
        ///    a certain "delay" period
        ///////////////////////////////////////////////////////////////////////////////////////////
        private bool IsNotKeyBounce(Keys thekey, double delay)
        {
            bool OKtoPress = true;
            if (_keyBounceDict.ContainsKey(thekey))
            {
                TimeSpan ts = DateTime.Now - _keyBounceDict[thekey];
                if (ts.TotalMilliseconds < _tsKeyBounceTiming)
                {
                    OKtoPress = false;
                }
                else
                {
                    DateTime dummy;
                    _keyBounceDict.TryRemove(thekey, out dummy);
                }
            }
            else
            {
                _keyBounceDict.AddOrUpdate(thekey, DateTime.Now, (key, oldValue) => oldValue);
            }
            return OKtoPress;
        }
    

    Here is what I put in my Update method:

                if (Keyboard.GetState().IsKeyDown(Keys.W))
            {
                if (IsNotKeyBounce(Keys.W, 50.0)) _targetNew.Distance *= 1.1f;
            }
    

    I use 50 ms, but you could use whatever makes sense for your app or tie it to GameTime or whatever...

提交回复
热议问题