Game Development Reference
In-Depth Information
We know that the digit 1 has a width of 20 pixels. The next character of our string would have
to be rendered at (20 + 20,100). In the case of the string “1. 100,� this character is the dot, which
has a width of 10 pixels in the numbers.png image:
game.getGraphics().drawPixmap(Assets. numbers , 40, 100, 200, 0, 10, 32);
The next character in the string needs to be rendered at (20 + 20 + 10,100). That character is a
space, which we don't need to draw. All we need to do is advance on the x axis by 20 pixels
again, as we assume that's the width of the space character. The next character, 1, would
therefore be rendered at (20 + 20 + 10 + 20,100). See a pattern here?
Given the coordinates of the upper-left corner of our first character in the string, we can loop
through each character of the string, draw it, and increment the x coordinate for the next
character to be drawn by either 20 or 10 pixels, depending on the character we just drew.
We also need to figure out which portion of the numbers.png image we should draw, given the
current character. For that, we need the x and y coordinates of the upper-left corner of that
portion, as well as its width and height. The y coordinate will always be 0, which should be
obvious when looking at Figure 6-1 . The height is also a constant—32 in our case. The width is
either 20 pixels (if the character of the string is a digit) or 10 pixels (if it is a dot). The only thing
that we need to calculate is the x coordinate of the portion in the numbers.png image. We can do
that by using the following neat little trick.
The characters in a string can be interpreted as Unicode characters or as 16-bit integers. This
means that we can actually do calculations with those character codes. By a lucky coincidence,
the characters 0 to 9 have ascending integer representations. We can use this to calculate the x
coordinate of the portion of the number.png image for a digit like this:
char character = string.charAt(index);
int x = (character - '0') * 20;
That will give us 0 for the character 0, 3 Ă— 20 = 60 for the character 3, and so on. That's exactly
the x coordinate of the portion of each digit. Of course, this won't work for the dot character,
so we need to treat that specially. Let's summarize this in a method that can render one of our
high-score lines, given the string of the line and the x and y coordinates where the rendering
should start:
public void drawText(Graphics g, String line, int x, int y) {
int len = line.length();
for ( int i = 0; i < len; i++) {
char character = line.charAt(i);
if (character == ' ') {
x += 20;
continue ;
}
int srcX = 0;
int srcWidth = 0;
if (character == '.') {
srcX = 200;
Search WWH ::




Custom Search