Game Development Reference
In-Depth Information
Displaying Text
In a game, we might want to display text on the screen in addition to sprites, physics bodies, and so
on. We use the print or the printf function available in the love.graphics library. Here's an example
of the print function:
love.graphics.print("Hello world", 10, 10)
And here's the printf function:
love.graphics.printf("Hello World finally but right aligned", 25, 45, 30, "right")
As mentioned, this needs to be in the love.draw function; otherwise, it won't be visible on the
screen.
The print function just draws the text on the screen at the x,y-coordinates provided, whereas the
printf function draws text that is formatted and also wrapped and aligned. The syntax for the
printf function is
printf(text, x, y, width, alignment)
The alignment is a string that can be left , right , or center , while the width specifies the width of
the text; any text that exceeds this value gets wrapped automatically.
As described earlier, in the "Images" section, we can set the color via the love.graphics.setColor
function. This will set the color for all objects drawn subsequently. So, the way to manage this is to
set the color for every object before it is drawn.
To print the seven colors of the rainbow, we can use
lg = love.graphics
lgc = love.graphics.setColor
function love.load()
lg.setBackgroundColor(255,255,255)
end
function love.draw()
lgc(141,56,201) -- Violet
lg.print("Violet", 10,10)
lgc(46,08,84) -- Indigo
lg.print("Indigo", 10,30)
lgc(0,0,255) -- Blue
lg.print("Blue", 10,50)
lgc(0,255,0) -- Green
lg.print("Green", 10,70)
lgc(255,255,0) -- Yellow
lg.print("Yellow", 10,90)
lgc(255,165,0) -- Orange
lg.print("Orange", 10,110)
lgc(255,0,0) -- Red
lg.print("Red", 10,130)
end
 
Search WWH ::




Custom Search