Создаем часы, показывающие минуты и секунды, используя Cocos2d

Создаем объект класса LabelAtlas, который будет отвечать за вывод времени и инициализируем вызов метода tick каждую секунду.
float gameTime = 0;
LabelAtlas *label = [[LabelAtlas alloc] initWithString:@"00:00" charMapFile:@"numbers.png" itemWidth:16 itemHeight:16 startCharMap:'.'];
[self schedule: @selector(tick:) interval:1.0];

Описываем обработчик, который будет срабатывать каждую секунду
-(void) tick: (ccTime) dt
{
gameTime = gameTime+1;

//Get the int value for total seconds
int seconds = [[NSNumber numberWithFloat:gameTime] intValue];

//Get the minutes
int realMinutes = seconds / 60;
//Get the seconds left over after you find the total minutes
int realSeconds = seconds % 60;

// Create strings to hold the string value of minutes and seconds
NSString *minutesString = @"%d";
NSString *secondsString = @"%d";

//Add zeros to minutes and seconds if less than ten so time always follows 00:00 format
if(realMinutes < 10) minutesString = @"0%d";
if(realSeconds < 10) secondsString = @"0%d";

//Add the strings together for display The dot is used to grab the colon from the number.png
//using the dot just grabs the first 16x16 section of numbers.png for display.
NSString *timeString = [[minutesString stringByAppendingString:@"."] stringByAppendingString:secondsString];

// Add the string to the label with the calculated minutes and seconds
[label setString:[NSString stringWithFormat:timeString, realMinutes, realSeconds]];
}

В проект следует добавить файл numbers.png

0 коммент.:

Отправить комментарий