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

Author Topic: Key repeats still occur even when set to false  (Read 1027 times)

0 Members and 1 Guest are viewing this topic.

grhomb

  • Newbie
  • *
  • Posts: 2
    • View Profile
Key repeats still occur even when set to false
« on: December 31, 2024, 12:14:15 am »
I'm trying to make it so the character moves a set distance when a key is pressed, but it keeps sliding even though i used window.setKeyRepeatEnabled(false)
(I'm using version 2.6)

code:
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Window");
    window.setKeyRepeatEnabled(false);
    sf::Sprite sprite;
    sf::Texture texture;
   
    if (!texture.loadFromFile("Awsome.png", sf::IntRect(10, 10, 320, 320)))
    {
        printf("failed to load");
    }
    sprite.setTextureRect(sf::IntRect(170, 100, 100, 100));
    sprite.setColor(sf::Color(255, 255, 2, 255));
    sprite.setTexture(texture);

    window.setVerticalSyncEnabled(true);

    while (window.isOpen()) {
        sf::Event event;
       
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }
        }
        if (event.type == sf::Event::KeyPressed) {
           
            if (event.key.code == sf::Keyboard::Left) {
                sprite.move(-30.f, 0.f);
            }
            if (event.key.code == sf::Keyboard::Right) {
                sprite.move(30.f, 0.f);
            }
        }
        window.clear(sf::Color::Black);
        window.draw(sprite);
        window.display();
    }
    return 0;
}
« Last Edit: December 31, 2024, 02:15:20 am by grhomb »

kojack

  • Sr. Member
  • ****
  • Posts: 354
  • C++/C# game dev teacher.
    • View Profile
Re: Key repeats still occur even when set to false
« Reply #1 on: December 31, 2024, 06:16:26 am »
One thing to fix is your key check is outside of the event loop, so it will miss keys if several events arrive in the one update. Otherwise you are checking the last event received, not every event received.
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }
            if (event.type == sf::Event::KeyPressed) {
                if (event.key.code == sf::Keyboard::Left) {
                    sprite.move(-30.f, 0.f);
                }
                if (event.key.code == sf::Keyboard::Right) {
                    sprite.move(30.f, 0.f);
                }
            }
        }

grhomb

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Key repeats still occur even when set to false
« Reply #2 on: December 31, 2024, 03:14:57 pm »
Thanks, somehow I just didn't see which curly brace corresponded to the loop before