Hello. Apparently, making an automatic line break for a string isn't as easy as I had thought.
I tried using this code:
int main()
{
sf::RenderWindow wnd(sf::VideoMode(640, 480, 32), "Video Game");
int sizeOfLine = 0;
int xPosition = 0; int yPosition = 0;
char previousChar, currentChar;
int fontSize = 24;
std::vector<sf::Sprite> characters;
sf::Sprite temporarySprite;
sf::Font font;
sf::Glyph glyph;
font.loadFromFile("font.ttf");
std::string msg("Hello! This is a text message. Because this message is so long, there has to be a line break somewhere.");
for (int i = 0; i < msg.length(); i++)
{
currentChar = msg[i];
glyph = font.getGlyph(currentChar, fontSize, false);
temporarySprite.setTexture(font.getTexture(fontSize));
temporarySprite.setTextureRect(glyph.textureRect);
if (i >= 1) { xPosition += font.getKerning(previousChar, currentChar, fontSize); }
sizeOfLine += temporarySprite.getTextureRect().width;
// THIS IS THE PART THAT REALLY MATTERS
if (sizeOfLine + fontSize >= wnd.getSize().x)
{
yPosition += font.getLineSpacing(fontSize);
xPosition = 0;
sizeOfLine = 0;
}
temporarySprite.setPosition(xPosition, yPosition + glyph.bounds.top + font.getGlyph('A', fontSize, false).bounds.height);
characters.push_back(temporarySprite);
xPosition += glyph.advance;
previousChar = currentChar;
}
}
But it doesn't work as well as I had hoped. What can I do?