I am trying to make a typewriter text effect. Here's the simplified code:
#include <SFML/Graphics.hpp>
void typewriter(sf::Text& something, sf::Font& f, sf::RenderWindow& w, std::string text, unsigned int characterSize, int positionX, int positionY, sf::Time td)
{
something.setCharacterSize(characterSize);
something.setPosition(positionX, positionY);
something.setFillColor(sf::Color::White);
something.setFont(f);
std::string s = "";
for (char c : text)
{
s = s + c;
something.setString(s);
w.clear();
w.draw(something);
sf::sleep(td);
w.display();
}
}
int main()
{
bool tw = true; //should typewriter be called
bool j = false;
std::string u;
//window
sf::RenderWindow window(sf::VideoMode(640, 480), "Problem with input", sf::Style::Default);
window.setFramerateLimit(60); //framerate limit is set to 60fps
//font
sf::Font font;
font.loadFromFile("oldFont.ttf");
//text
sf::Text enterSomething;
sf::Text input;
input.setFont(font);
input.setCharacterSize(25);
input.setPosition(75, 400);
input.setFillColor(sf::Color::White);
//events
sf::Event event;
//main loop
while (window.isOpen())
{
window.clear();
if (tw)
{
typewriter(enterSomething, font, window, "Enter something:", 25, 200, 100, sf::milliseconds(200));
tw = false;
j = true;
}
else
{
window.draw(enterSomething);
}
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
else if (event.type == sf::Event::TextEntered && j)
{
if (event.text.unicode >= 32 && event.text.unicode <= 126)
{
u = u + static_cast<char>(event.text.unicode);
}
else if (event.text.unicode == 8 && !u.empty())
{
u.pop_back();
}
}
}
input.setString(u);
window.draw(input);
window.display();
}
}
This is the problem: if the user starts typing while "Enter something:" is being displayed, whatever he/she typed at that moment will be later displayed to the screen.
I tried placing TextEntered block into another event block but the result was same (probably because I didn't do it properly).