Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: KeyReleased is repeating  (Read 1670 times)

0 Members and 1 Guest are viewing this topic.

Apocrypha

  • Newbie
  • *
  • Posts: 1
    • View Profile
KeyReleased is repeating
« on: December 28, 2020, 06:07:55 pm »
From what I read I should use KeyReleased when I want to trigger an action exacly once. And for some reason when I use KeyReleased there is a repeat and I don't really know how I can fix it.


   void example() {
      if (event->type == sf::Event::KeyReleased) {
         if (event->key.code == sf::Keyboard::Up) {
            std::cout << "UP!" << std::endl;
         }
         else if (event->key.code == sf::Keyboard::Down) {   
            std::cout << "DOWN!" << std::endl;
         }
      }
   }

When I am releasing a key then I get multiple UP! or DOWN! when I only wanted one action per released key and the number of actions it returns is completly random sometimes I get 20, sometimes 50, sometimes maybe 3 and on really rare occasions it works as it should and I get 1. Do somebody know what is going on?

Stauricus

  • Sr. Member
  • ****
  • Posts: 369
    • View Profile
    • A Mafia Graphic Novel
    • Email
Re: KeyReleased is repeating
« Reply #1 on: December 28, 2020, 06:26:42 pm »
you are forgetting to poll the events with "while (window.pollEvent(event))". working example:

#include <iostream>
#include <SFML/Graphics.hpp>

int main(){
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML");

    while (window.isOpen()){
            sf::Event event;
            while (window.pollEvent(event)){
                if (event.type == sf::Event::Closed){
                        window.close();
                }
                if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Up){
                    std::cout << "UP! ";
                }
            }
            window.clear(sf::Color::Black);
            window.display();
    }

    return 0;
}
 
Visit my game site (and hopefully help funding it? )
Website | IndieDB