How to slow down or stop key presses in XNA

后端 未结 12 2118
北恋
北恋 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-01 06:05

    I thought the previous answers were a bit over-complicated, so I'm giving this one here...

    Copy the KeyPress class below in a new file, declare the KeyPress variables, initialize them in your Initialize() method. From there you can do if ([yourkey].IsPressed()) ...

    Note: this answer works only for Keyboard input, but it should be easily ported to Gamepad or any other input. I think keeping the code for the different types of input separate is better.

    public class KeyPress
    {
        public KeyPress(Keys Key)
        {
            key = Key;
            isHeld = false;
        }
    
        public bool IsPressed { get { return isPressed(); } }
    
        public static void Update() { state = Keyboard.GetState(); }
    
        private Keys key;
        private bool isHeld;
        private static KeyboardState state;
        private bool isPressed()
        {
            if (state.IsKeyDown(key))
            {
                if (isHeld) return false;
                else
                {
                    isHeld = true;
                    return true;
                }
            }
            else
            {
                if (isHeld) isHeld = false;
                return false;
            }
        }
    }
    

    Usage:

    // Declare variable
    KeyPress escape;
    
    // Initialize()
    escape = new KeyPress(Keys.Escape)
    
    // Update()
    KeyPress.Update();
    if (escape.IsPressed())
        ...
    

    I might be wrong, but I think my answer is easier on resources than the accepted answer and also more readable!

提交回复
热议问题