0

For some reason, pressed / released keys are not recognized. Only the isKeyHeld method works well. The update method is called before validating the input. What have I done wrong?

        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);
        }
novadinn
  • 1
  • 2
  • 2
    What are you trying to do here _previous_held_heys__ _= held_heys_;_ this is not a copy of the data but an assignment of the second reference to the first. In other words the two variables reference the same data – Steve Nov 13 '21 at 11:07

1 Answers1

2

Since HashSet<T> is a reference type, your assignment just copies reference, not data:

previous_held_heys_ = held_heys_;

It is important to understand the difference between reference and value types (official doc.) and this related question with a nice answer.

You could copy data as follows:

previous_held_heys_.Clear();
previous_held_heys_.UnionWith(held_heys_);
Cleptus
  • 3,446
  • 4
  • 28
  • 34
Dmitry
  • 13,797
  • 6
  • 32
  • 48