novadinn
novadinn

Reputation: 1

Why are the previous input keys not recognized?

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);
        }

Upvotes: 0

Views: 38

Answers (1)

Dmitry
Dmitry

Reputation: 14059

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_);

Upvotes: 2

Related Questions