Question

So I've downloaded SFML and so far love it. I've run into a roadblock and am trying to figure out how to implement a blinking cursor into the code below. I also need to figure out how to print a single char (when the user presses a key on the keyboard) onto the window. Here's some code I've used ever since I've downloaded SFML 2.0:

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

int main() {
    sf::RenderWindow wnd(sf::VideoMode(650, 300), "SFML Console");
    sf::Vector2u myVector(650, 300);
    wnd.setSize(myVector);

    sf::Font myFont;
    myFont.loadFromFile("theFont.ttf");

    sf::Color myClr;
    myClr.r = 0;
    myClr.g = 203;
    myClr.b = 0;

    sf::String myStr = "Hello world!";
    std::char myCursor = '_';

    sf::Text myTxt;
    myTxt.setColor(myClr);
    myTxt.setString(myStr);
    myTxt.setFont(myFont);
    myTxt.setCharacterSize(12);
    myTxt.setStyle(sf::Text::Regular);
    myTxt.setPosition(0, 0);

    std::int myCounter = 0;

    while(wnd.isOpen()) {
        sf::Event myEvent;

        while (wnd.pollEvent(myEvent)) {
            if (myEvent.type == sf::Event::Closed) {
                wnd.close();
            }

            if (myEvent.type == sf::Event::KeyPressed) {
                if (myEvent.key.code == sf::Keyboard::Escape) {
                    wnd.close();
                }
            }

            wnd.clear();
            wnd.draw(myTxt);

            myCounter++;
            std::if (myCounter >= 1000) {
                myCounter = 0;
            }

            std::if (myCounter < 1000) {
                myTxt.setString("Hello world!_");
            }

            wnd.display();
        }
    }
}
Was it helpful?

Solution

Use sf::Clock (doc).

Declare your clock along with your other variables before your main loop, this also starts the clock automatically. In your loop, check for the time elapsed and reset the clock if it exceeds what you want. Example :

sf::Clock myClock; // starts the clock
bool showCursor = false;

// ...

wnd.draw(myTxt);

if(clock.getElapsedTime() >= sf::milliseconds(500))
{
    clock.restart();
    showCursor = !showCursor;
    if(showCursor)
        myTxt.setString("Hello World!_");
    else
        myTxt.setString("Hello World!");
}

// ...

This should give you a cursor blinking by 0.5 second.

By the way, why are you using std::if() instead of a plain if that is included in the language ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top