How to slow down or stop key presses in XNA

后端 未结 12 2154
北恋
北恋 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 06:07

    Well what you could do is something like this (Also will track every key)

    int[] keyVals;
    TimeSpan pressWait = new TimeSpan(0, 0, 1);
    Dictionary keyDowns = new Dictionary();
    Dictionary keyTimes = new Dictionary();
    
    public ConstructorNameHere
    {
        keyVals = Enum.GetValues(typeof(Keys)) as int[];
        foreach (int k in keyVals)
        {
            keyDowns.Add((Keys)k, false);
            keyTimes.Add((Keys)k, new DateTime()+ new TimeSpan(1,0,0));
        }
    }
    
    protected override void Update(GameTime gameTime)
    {
        foreach (int i in keyVals)
        {
            Keys key = (Keys)i;
            switch (key)
            {
                case Keys.Enter:
                    keyTimes[key] = (Keyboard.GetState().IsKeyUp(key)) ? ((keyDowns[key]) ? DateTime.Now + pressWait : keyTimes[key]) : keyTimes[key];
                    keyDowns[key] = (keyTimes[key] > DateTime.Now) ? false : Keyboard.GetState().IsKeyDown(key);
    
                    if (keyTimes[key] < DateTime.Now)
                    {
                        // Code for what happens when Keys.Enter is pressed goes here.
                    }
                    break;
        }
    }
    

    By doing it this way you're able to check every key. You could also do this for just every key by create separate DateTimes and seperate bool values.

提交回复
热议问题