Game Development Reference
In-Depth Information
Getting started with sf::Text
Text is one of the most overlooked
features
of a game, but it is sometimes essential to the
gaming experience—for example, using the correct font and size, displaying the appropri-
ate amount of information, and so on. Yes, there are games where text is not used at all, but
those are quite rare. If you make a game, you'll need to render text at some point during the
development process (even for debugging data). In this section, we will talk about text and
fonts.
Remember the
Sprite
—
Texture
and
Sound
—
SoundBuffer
relation? Take a guess
which other part of SFML uses the same model. Yes, you're right—the
sf::Font
and
sf::Text
classes. In this case, the
Font
class is the resource which we want to keep
safe while the
Text
class uses it. You should probably be able to picture the process of
loading fonts and creating texts based on the fact that this is the third time that we've come
across it. If you can't—don't worry, this is what this topic is for. Let's start by creating a
simple text label:
Once we have an instance of
Text
, we can draw it by calling the
RenderWin-
dow::draw()
method. In fact, like the
Sprite
and
Shape
classes, the
Text
class in-
herits from
sf::Drawable
and
sf::Transformable
so we can transform it in the
same manner by changing its position, rotation, scale, and origin.
We can set a few text-specific properties on a
Text
object. One of the important ones is
the character size. This property determines how tall the characters are (in pixels) and it's
set by calling
Text::setCharacterSize()
. We can also specify a third argument in
the constructor which changes the character size with the creation (the default value is 30).
Additionally, we can change the string, which is displayed by the text object. This is done
through
Text::setString()
. It expects a
sf::String
object, which has implicit