Using Texture2D class to generate scores

When you are using Texture2D class in your app and you need to fast generate numbers like scores, it’s not good to release and init texture all the time:

int score = 10;

[texture release];

texture = [[Texture2D alloc] initWithString:[NSString stringWithFormat: @”%d”, score] dimensions:CGSizeMake(320,30) alignment:UITextAlignmentCenter fontName:@”Marker Felt” fontSize:16];

// Wrong

But you can use a little trick. Just keep in memory all figures 0 – 9 and “build” your number using %. It’s a very fast way which uses not much memory.

//init textures
for (int i = 0 ; i < 10; i++) texture[i] = [[Texture2D alloc] initWithString:[NSString stringWithFormat: @"%d", i] dimensions:CGSizeMake(30,30) alignment:UITextAlignmentCenter fontName:@"Marker Felt" fontSize:20];

// generate number;

int score = 895024;

int n = 10;
int a = 0;

[texture[score % 10] drawAtPoint:CGPointMake(310,460)];

while ((score % n) != score)
{
a++;
[texture[( (h % (n*10)) – (h % n) ) / n ] drawAtPoint:CGPointMake(310 -15*a , 460)];
n*= 10;
}

This method draws a score starting in point 310,460 and moves to the right. Of course you can modify and draw it in way you want.

It’s a very simple thing:

895024 % 10 = 4

next:

((895024 % 100) – (895024 % 10))/10 = 2

etc:).

Leave a comment