【问题标题】:Why are the previous input keys not recognized?为什么以前的输入键无法识别?
【发布时间】:2021-12-25 10:22:43
【问题描述】:

由于某种原因,无法识别按下/释放的键。只有 isKeyHeld 方法运作良好。在验证输入之前调用更新方法。我做错了什么?

        HashSet<Keys> held_heys_ = new HashSet<Keys>();
        HashSet<Keys> previous_held_heys_ = new HashSet<Keys>();

        public void beginNewFrame() {
            previous_held_heys_ = held_heys_;
            held_heys_.Clear();
        }

        public void update(Keys[] keys) {
            foreach(Keys key in keys) {
                held_heys_.Add(key);
            }
        }

        public bool isKeyHeld(Keys key) {
            return held_heys_.Contains(key);
        }
        public bool wasKeyPressed(Keys key) {
            return !previous_held_heys_.Contains(key) && held_heys_.Contains(key);
        }
        public bool wasKeyReleased(Keys key) {
            return previous_held_heys_.Contains(key) && !held_heys_.Contains(key);
        }

【问题讨论】:

  • 你想在这里做什么 previous_held_heys_ =held_heys;_ 这不是数据的副本,而是第二次引用的分配首先。换句话说,这两个变量引用了相同的数据

标签: c# input monogame


【解决方案1】:

由于HashSet&lt;T&gt; 是一个引用类型,你的赋值只是复制引用,而不是数据:

previous_held_heys_ = held_heys_;

了解reference and value types (official doc.)this related question with a nice answer 之间的区别很重要。

您可以按如下方式复制数据:

previous_held_heys_.Clear();
previous_held_heys_.UnionWith(held_heys_);

【讨论】:

    猜你喜欢
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多