Lets say i have a sprite sheet of numbers 0-9 and i want to draw an image for the score of my game. So if my score is 250 i want to draw a 2 a 5 and then a 0. I am just extremely confused on how i would do this. i have been thinkning about it for a day now and I couldnt think of anything… any advice? or other ways of achieveing this goal?
It really isn’t as difficult as you are making it seem. Each image has a width.
Let’s say #2 has 40 pixels, and #5 has 30 pixels, and #0 has 35 pixels.
You choose a spot where you want to display the score. Let’s say (10, 100).
Display #2 at (10, 100).
#5 has to be displayed right next to the first number drawn.
So you add the #2 width to the display value.
Display #5 at (10+40, 100) or (50, 100).
#0 has to be displayed past both numbers.
So you add the #2 and the #5 width to the first number drawn.
Display #5 at (10 + 40 + 35, 100) or (85, 100).
This will get your score images to display right next to each other. Hope it makes sense.
Well, the above solution isn’t the best, and it can be greatly simplified. For organization and efficiency, its best if you have a strip image where each number has the same width(align all the numbers to the right).
If you have an integer score, convert that to a string. Loop through each character in the string and use an approach like this:
int sx = 0, sy = 0;
for(int i = 0; i < str.length(); i++) {
int pos = Integer.valueOf(str.substring(i, i));
BufferedImage curnum = bitmapfont.getSubImage(pos * fontwidth, 0, fontwidth, fontheight);
g.render(curnum, sx, sy, null);
sx += fontwidth;
}
Play with that and you’ll get what you want.
woot! your aweomse lol thats actually a very good solution !
ok so after trying to implement it i am having some problems. when replacing your str string with my score string this error comes up: Cannot invoke substring(int, int) on the primitive type int .
also could you explain the curnum image to me? i dont understand it too well
Okay, so in your bitmap font, the numbers should go from 0 - 9. So basically, if you take your score, take each character and convert it to an integer, you can just get that frame from the bitmap font.
If the current number is 0, 0th frame of the bitmap font
If the current number is 8, 8th frame of the bitmap font
If you have an Integer score, String str = String.valueOf(score);
thanks a bunch man! this worked great