Thursday, June 30, 2011

Converting an Integer to an Int Array

During game development one thing that you want to avoid as much as possible is allocating memory in your main game loop.  One item that typically changes often during game play is the user's score.  In order to avoid creating new objects to store the user's updated score value, you can store each digit of the new score in an array.  Then use a simple method to display the portion of your texture, or image graphic, that maps to each digit.  The method that I used to convert from an Integer to an int array is shown below.

public static void setScore(int[] score, int points) {
int temp = points;
int i = 0;
while (temp > 0) {
score[i] = temp % 10;
temp /= 10;
i++;
}
}