Game Development Reference
In-Depth Information
int
c = text.charAt(i) - ' ';
if
(c < 0 || c > glyphs.length - 1)
continue
;
TextureRegion glyph = glyphs[c];
batcher.drawSprite(x, y, glyphWidth, glyphHeight, glyph);
x += glyphWidth;
}
}
}
The
drawText()
method takes a
SpriteBatcher
instance, a line of text, and the x and y positions
at which to start drawing the text. The x and y coordinates specify the center of the first glyph.
All we do is get the index for each character in the string, check whether we have a glyph for it,
and, if so, render it via the
SpriteBatcher
. We then increment the x coordinate by the
glyphWidth
so that we can start rendering the next character in the string.
You might wonder why we don't need to bind the texture containing the glyphs. We assume that
this is done before a call to
drawText()
. The reason is that the text rendering might be part of a
batch, in which case the texture must already be bound. Why unnecessarily bind it again in the
drawText()
method? Remember, OpenGL ES loves nothing more than minimal state changes.
Of course, we can only handle fixed-width fonts with this class. If we want to support more
general fonts, we also need to have information about the advance of each character. One
solution would be to use kerning, as described in the earlier section “Handling Text with Bitmap
Fonts.� We are happy with our simple solution though.
The GLScreen Class
In the examples in the previous two chapters, we always got the reference to
GLGraphics
by
casting. Let's fix this with a little helper class called
GLScreen
, which will do the dirty work for us
and store the reference to
GLGraphics
in a member. Listing 9-5 shows the code.
Listing 9-5. GLScreen.java, a Little Helper Class
package
com.badlogic.androidgames.framework.impl;
import
com.badlogic.androidgames.framework.Game;
import
com.badlogic.androidgames.framework.Screen;
public abstract class GLScreen extends Screen {
protected final
GLGraphics glGraphics;
protected final
GLGame glGame;
public
GLScreen(Game game) {
super
(game);
glGame = (GLGame)game;
glGraphics = glGame.getGLGraphics();
}
}