Debug label y value in cocos2d is off - iphone

I have a cocos2d game with a CCLayer called GameplayLayer placed inside a scene. Here is the layer's init code:
- (id)initWithScene1BackgroundLayer:(Scene1BackgroundLayer *)scene5UILayer {
if ((self = [super init])) {
uiLayer = scene5UILayer;
startTime = CACurrentMediaTime();
[self scheduleUpdate];
self.isAccelerometerEnabled = YES;
//chipmunk
[self createSpace];
[self createGround];
mouse = cpMouseNew(space);
self.isTouchEnabled = YES;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[[CCSpriteFrameCache sharedSpriteFrameCache]
addSpriteFramesWithFile:#"escapesceneatlas.plist"];
sceneSpriteBatchNode = [CCSpriteBatchNode
batchNodeWithFile:#"escapesceneatlas.png"];
hopper = [[[CPHopper alloc] initWithLocation:ccp(200,200) space:space groundBody:groundBody] autorelease];
} else {
[[CCSpriteFrameCache sharedSpriteFrameCache]
addSpriteFramesWithFile:#"escapesceneatlas.plist"];
sceneSpriteBatchNode = [CCSpriteBatchNode
batchNodeWithFile:#"escapesceneatlas.png"];
//Viking became hopper and starts at bottom
hopper = [[[CPHopper alloc] initWithLocation:ccp(100,100) space:space groundBody:groundBody] autorelease];
//An enemy robot called JJ1 also starts at bottom
genericBody = [[[CPGenericBody alloc] initWithLocation:ccp(210,200) space:space groundBody:groundBody] autorelease];
//add the batchnode to layer
[self addChild:sceneSpriteBatchNode z:0];
}
[self addLabel];
[sceneSpriteBatchNode addChild:hopper z:2];
[sceneSpriteBatchNode addChild:genericBody z:2];
}
return self;
}
The addLabel method calls the debugLabel of the hopper class like this:
-(void)addLabel{
//set debuglabel
CCLabelBMFont *debugLabel=[CCLabelBMFont labelWithString:#"NoneNone" fntFile:#"SpaceVikingFont.fnt"];
[self addChild:debugLabel];
[hopper setMyDebugLabel:debugLabel];
}
Then the debugLabel code in the hopper class is:
-(void)setDebugLabelTextAndPosition {
CGPoint newPosition = [self position];
NSString *labelString = [NSString stringWithFormat:#"X: %.2f \n Y:%d \n", newPosition.x, newPosition.y];
[myDebugLabel setString: [labelString stringByAppendingString:#" tracking..."]];
float yOffset = screenSize.height * 0.195f;
newPosition = ccp(newPosition.x,newPosition.y+yOffset);
[myDebugLabel setPosition:newPosition];
}
For some reason when I run it the X value is fine, its value seems reasonable, it starts out at 100 but the y value is approx 1,567,385 and then if i move the hopper it goes to 35,633,753 and keeps changing to huge random numbers. It seems very unsteady.
Why could this be?

There is a simple typo in your debug label code. You are formatting your floating point number as an integer which just gives garbage results. Because the stringWithFormat function will not implicitly convert the float to int but just take the bit representation of the float and interpret it as an integer number.
A more detailed explanation is given here.
So this
NSString *labelString = [NSString stringWithFormat:#"X: %.2f \n Y:%d \n", newPosition.x, newPosition.y];
should be
NSString *labelString = [NSString stringWithFormat:#"X: %.2f \n Y:%.2f \n", newPosition.x, newPosition.y];
.

Related

How to generate images from already recorded video using AVAssetImageGeneratorCompletionHandler block?

This might be a silly question but sorry for that as i am a newbie to iPhone.
I want to generate images for every frames of video and display that in UIScrollview inside UIImageView.
When i am trying to do that i am getting memory warning and my app crashes.
Below is my code.
- (IBAction)onCameraButtonPressed:(id)sender
{
// Initialize UIImagePickerController to select a movie from the camera roll.
UIImagePickerController *videoPicker = [[UIImagePickerController alloc] init];
videoPicker.delegate = self;
videoPicker.modalPresentationStyle = UIModalPresentationCurrentContext;
videoPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
videoPicker.mediaTypes = #[(NSString*)kUTTypeMovie];
[self presentViewController:videoPicker animated:YES completion:nil];
}
#pragma mark Image Picker Controller Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
currentVideoURL = info[UIImagePickerControllerReferenceURL];
//Video URL = assets-library://asset/asset.MOV?id=D0A4A3EE-C5F3-49C8-9E45-ADF775B9FA8C&ext=MOV
//NSLog(#"Video URL = %#",currentVideoURL);
//imageIndex = 0;
for (UIImageView *subView in thumbnailScrollView.subviews)
{
[subView removeFromSuperview];
}
[self generateThumbnailsFromVideoURL:currentVideoURL];
//[self generateAVAssetThumbnails:currentVideoURL];
//[self appleImageGenerator:currentVideoURL];
}
- (void)generateThumbnailsFromVideoURL:(NSURL *)videoURL
{
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:videoURL options:nil];
//NSLog(#"Video duration %lld seconds",asset.duration.value/asset.duration.timescale);
int videoDuration = (asset.duration.value/asset.duration.timescale);
if (cmTimeArray.count>0) {
[cmTimeArray removeAllObjects];
}
for (int i = 0; i<videoDuration; i++)
{
int64_t tempInt = i;
CMTime tempCMTime = CMTimeMake(tempInt,1);
int32_t interval = 15;
for (int j = 1; j<16; j++)
{
CMTime newCMtime = CMTimeMake(j,interval);
CMTime addition = CMTimeAdd(tempCMTime, newCMtime);
[cmTimeArray addObject:[NSValue valueWithCMTime:addition]];
}
}
//NSLog(#"Array of time %# count = %d",cmTimeArray, cmTimeArray.count);
/*for(int t=0;t < asset.duration.value;t++) {
CMTime thumbTime = CMTimeMake(t,asset.duration.timescale);
NSValue *v=[NSValue valueWithCMTime:thumbTime];
[cmTimeArray addObject:v];
}
NSLog(#"Array of time %# count = %d",cmTimeArray, cmTimeArray.count);*/
__block int i = 0;
//__block UIImage *currentImage = nil;
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result == AVAssetImageGeneratorSucceeded) {
// currentImage = [UIImage imageWithCGImage:im];
//[framesArray addObject:[UIImage imageWithCGImage:im]];
[self performSelectorOnMainThread:#selector(insertImageToScrollView:) withObject:[UIImage imageWithCGImage:im] waitUntilDone:NO];
}
else
NSLog(#"Ouch: %#", error.description);
i++;
imageIndex = i;
if(i == cmTimeArray.count) {
//[self performSelectorOnMainThread:#selector(insertImageToScrollView:) withObject:framesArray waitUntilDone:YES];
}
};
// Launching the process...
self.generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
self.generator.appliesPreferredTrackTransform=TRUE;
self.generator.requestedTimeToleranceBefore = kCMTimeZero;
self.generator.requestedTimeToleranceAfter = kCMTimeZero;
self.generator.maximumSize = CGSizeMake(40, 40);
[self.generator generateCGImagesAsynchronouslyForTimes:cmTimeArray completionHandler:handler];
}
-(void)insertImageToScrollView:(UIImage *)image
{
int xPosition = (5*imageIndex)+(WIDTH*imageIndex)+OFFSET;
UIImageView *currentImageView = [[UIImageView alloc]initWithFrame:CGRectMake(xPosition, 5, WIDTH, WIDTH)];
currentImageView.tag = imageIndex+10;
currentImageView.image = image;
[thumbnailScrollView addSubview:currentImageView];
[thumbnailScrollView setContentSize:CGSizeMake(xPosition+WIDTH+5,thumbnailScrollView.frame.size.height)];
}
You are loading all images into the view, but only a few are displayed at any one given time. Depending on the amount of images, this could take up a LOT of memory.
You could consider the following approach:
Generate all the images and write them to local storage, store the file-urls of the images in an array.
Now for your scrollview, only add images as they are needed, when you scroll to the next ones. When adding images, you load them from disk and add them to your view. Take a look at this example code for a horizontal infinite scrollview: https://code.google.com/p/iphone-infinite-horizontal-scroller.
You could also use an ordinary UITableView with a custom cell, only showing the image.
I found my mistake. I was assigning original/full image to my 40*40 image view. That was generating memory warning. To solve provide required image size while generating image using below code.
self.generator.maximumSize = CGSizeMake(40, 40);

How to display the score in the game over layer in cocos2d

I've a problem when I try to show the final score in the Game Over Layer in a game in cocos2d. There's an algorithm that modify the value of my variable increment, that contains the points of the user and then the game shows them.
increment = increment + 50;
[pointLabel setString: [NSString stringWithFormat: #"Points: %i", increment]];
and then a function controls if the user has or not lives in his play
-(void)gameOver:(int)value punteggio:(id)punti{
if (value == 1) {
//WIN
}else if(value == 2){
if (life > 1) { // 1
life = life - 1;
for (CCSprite *spr in spriteLifeArray) {
if (life == spr.tag) {
[self removeChild:spr cleanup:YES];
}}}
else {
// LOSE
[...]
[[CCDirector sharedDirector] replaceScene:[GameOver node]];
}
}}
Then the GameOverLayer is called. This is the .h file
#interface GameOver : CCNode {
CGSize size;
CCLabelTTF *label1;
CCLabelTTF *label2;
CCLabelTTF *labelpnt;
CCLabelTTF *labelscore;
}
-(void)restart;
Here the .m file
#implementation GameOver
+(id) scene {
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
GameOver *layer = [GameOver node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init{
if( (self=[super init] )) {
size = [[CCDirector sharedDirector] winSize];
label1 = [CCLabelTTF labelWithString:#"Game Over" fontName:#"Marker Felt" fontSize:40];
label1.position = ccp(size.width/2 , size.height/2+20+50 );
labelpnt = [CCLabelTTF labelWithString:#"Punteggio" fontName:#"Marker Felt" fontSize:20];
labelpnt.position = ccp(size.width/2 , size.height/2+50-100 );
labelscore = [CCLabelTTF labelWithString:#"100" fontName:#"Marker Felt" fontSize:20];
[labelscore setString: [NSString stringWithFormat: #" 0 "]];
[labelscore setColor:ccc3(255, 1, 1)];
labelscore.position = ccp(size.width / 2, size.height/2+50-130);
label2 = [CCLabelTTF labelWithString:#"Ricomincia" fontName:#"Marker Felt" fontSize:25];
CCMenuItemLabel *back = [CCMenuItemLabel itemWithLabel:label2 target:self selector:#selector(restart)];
CCMenu *menu= [CCMenu menuWithItems:back, nil];
menu.position = ccp(size.width/2 , size.height/2-50+50);
[self addChild: label1];
[self addChild: labelpnt];
[self addChild: labelscore];
[self addChild: menu];
}
return self;
}
-(void) restart {
[[CCDirector sharedDirector] replaceScene:[HelloWorldLayer node]];
}
How can I show the final value of my int increment in the game over layer? How can I pass it throught the classes?
Use UserDefault. Here is code
//Save score in game screen
int highScore = 234;
[[NSUserDefaults standardUserDefaults] setInteger:12 forKey:#"HighScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
//get score in game over
int highScore = [[NSUserDefaults standardUserDefaults] integerForKey:#"HighScore"];
NSString *score = [NSString stringWithFormat: #"%d", highScore];
CCLabelTTF *scoreLabel = [CCLabelTTF labelWithString:score fontName:#"Marker Felt" fontSize:40];
Hey in that Case You should take a separate layer for displaying the Score lives or whatever you want to display simultaneously.
In HUD Layer i.e Heads-Up Display class You should write some basic code to display a CCLabelBMFont to the screen that says "Your Score", “You Win” or “You Lose” and a button underneath that says “Restart”.
When the restart button is tapped, it creates a new instance of the ActionLayer switches to it.
Write a Score method scoreUpdate, this method will have the logic for the score calculation like whenever a bullet hit to monster and update it to the CCLabelBMFont label.
And then All you need to do just call that method.
Here is the one of the best tutorial for such requirement.
See

Assertion failure Error when trying to stop sprite action in cocos2d iphone

I am having problem in stoping action. i have 2 sprite animation 1 is ant and second is grasshopper. WHen i am just calling ants animation it works fine but when i try to run both ant and grasshopper animation it gives me error.
* Assertion failure in -[CCSpriteBatchNode addChild:z:tag:], /Users/zohaib/Downloads/zohaibgame/zohaibgame/libs/cocos2d/CCSpriteBatchNode.m:183
it gives error when antMoveEnded is called.
ants animation code
-(void) walk_Ants
{
// 1) Cache the sprite frames and texture
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:
#"ant-animation.plist"];
/// 2) Create a sprite batch node
CCSpriteBatchNode *spriteSheet_ant = [CCSpriteBatchNode
batchNodeWithFile:#"ant-animation.png"];
[self addChild:spriteSheet_ant];
// 3rd Step
// 3) Gather the list of frames
NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = 1; i <= 24; ++i) {
[walkAnimFrames addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
[NSString stringWithFormat:#"%d.png", i]]];
}
// 4th Step
// 4) Create the animation object
CCAnimation *walkAnim = [CCAnimation
animationWithSpriteFrames:walkAnimFrames delay:0.05f];
// 5th Step
// 5) Create the sprite and run the animation action
self.ants = [CCSprite spriteWithSpriteFrameName:#"1.png"];
_ants.position = ccp(winSize.width, winSize.height/6);
//_ants.position = ccp(459, 16);
self.walkActionAnt = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim]];
[_ants runAction:_walkActionAnt];
[spriteSheet_ant addChild:_ants];
CCLOG(#"Position %#",NSStringFromCGPoint(_ants.position));
[self walkingAnts];
}
-(void) walkingAnts
{
// 2) Set the desired velocity
float antVelocity = 480.0/10.0;
// 3) Figure out the amount moved in X and Y
CGPoint waking_Path = CGPointMake(X_AXIS_ENDINGPATH, _ants.position.y);
CGPoint moveDifference = ccpSub(waking_Path, _ants.position);
// 4) Figure out the actual length moved
float distanceToMove = ccpLength(moveDifference);
// 5) Figure out how long it will take to move
float moveDuration = distanceToMove / antVelocity;
// 7) Run the appropriate actions
//[_ants stopAction:_moveAction];
id restartAntWalk = [CCCallFuncN actionWithTarget:self selector:#selector(antMoveEnded:)];
self.moveActionAnt = [CCSequence actions:
[CCMoveTo actionWithDuration:moveDuration position:waking_Path],
restartAntWalk,
nil];
//self.moveActionAnt.tag = 121;
[_ants runAction:_moveActionAnt];
_movingAnt = TRUE;
}
- (void) antMoveEnded: (ccTime) dt
{
if(_ants.position.x == -50)
{
[_ants stopAction:_moveActionAnt];
//[self stopActionByTag:121];
_movingAnt = FALSE;
[self walk_Ants];
}
}
GrassHopper code ( mantis )
-(void) mantisCome
{
float w_index = arc4random() % 480;
//float h_index = arc4random() % 320;
self.moveActionMantis = [CCSequence actions:
[CCMoveTo actionWithDuration:2 position:ccp(w_index, 63)],
nil];
[_mantis runAction:_moveActionMantis];
[self schedule:#selector(timer:) interval:5];
}
-(void) mantisGo
{
self.moveActionMantis = [CCSequence actions:
[CCMoveTo actionWithDuration:2 position:ccp(-50, 280)],
nil];
[_mantis runAction:_moveActionMantis];
[self unschedule:#selector(timer:)];
[self mantisAnimation];
}
#pragma -mark Mantis Animation
-(void) mantisAnimation
{
// 1) Cache the sprite frames and texture
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:
#"mantis-animation.plist"];
/// 2) Create a sprite batch node
CCSpriteBatchNode *spriteSheet_mantis = [CCSpriteBatchNode
batchNodeWithFile:#"mantis-animation.png"];
[self addChild:spriteSheet_mantis];
// 3rd Step
// 3) Gather the list of frames
NSMutableArray *walkAnimFrames_mantis = [NSMutableArray array];
for(int i = 1; i <= 14; ++i) {
[walkAnimFrames_mantis addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
[NSString stringWithFormat:#"%d.png", i]]];
}
// 4th Step
// 4) Create the animation object
CCAnimation *walkAnim_mantis = [CCAnimation
animationWithSpriteFrames:walkAnimFrames_mantis delay:0.05f];
// 5th Step
// 5) Create the sprite and run the animation action
self.mantis = [CCSprite spriteWithSpriteFrameName:#"1.png"];
_mantis.position = ccp(winSize.width+100, winSize.height+100);
_mantis.flipX=YES;
//_mantis.position = ccp(459, 16);
self.walkActionMantis = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim_mantis]];
walkAnim_mantis.restoreOriginalFrame = NO;
[_mantis runAction:_walkActionMantis];
[spriteSheet_mantis addChild:_mantis];
//CCLOG(#"Position %#",NSStringFromCGPoint(_mantis.position));
[self mantisCome];
}
I figured out what was the problem.
when i was creating animation for ant i was using this code
NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = 1; i <= 24; ++i) {
[walkAnimFrames addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
[NSString stringWithFormat:#"%d.png", i]]];
}
self.ants = [CCSprite spriteWithSpriteFrameName:#"1.png"];
and when creating animaiton for mantis
NSMutableArray *walkAnimFrames_mantis = [NSMutableArray array];
for(int i = 1; i <= 14; ++i) {
[walkAnimFrames_mantis addObject:
[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
[NSString stringWithFormat:#"%d.png", i]]];
}
self.mantis = [CCSprite spriteWithSpriteFrameName:#"1.png"];
i was using 1.png for both. self.ant and self.mantis. i created a new plist file and changed png name from 1.png to ant1.png . It works now.

array removeObjectsAtIndexes:

I have a problem, with deleting items from an array..
first:
i have a variable of type int, called zan. in my HelloWordScene.h
int zan;
NSMutableArray * targets;
NSMutableArray *projectiles;
in my HelloWordScene.m. i have an object, animated:
-(id) init {
if((self = [super init])) {
[self schedule:#selector(update:)];
_targets = [[NSMutableArray alloc] init];
_projectiles = [[NSMutableArray alloc] init];
}
[self schedule:#selector(gameLogic:) interval:3];
return self;
}
in my selector I increment the var:
-(void)gameLogic:(ccTime)dt {
[self addTarget];
zan ++;
}
Later I have an animation and I have a addTarget:
// This loads an image of the same name (but ending in png), and goes through the
// plist to add definitions of each frame to the cache.
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"zancudo.plist"];
// Create a sprite sheet with the images
CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:#"zancudo.png"];
[self addChild:spriteSheet];
// Load up the frames of our animation
NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = 0; i <= 4; ++i) {
[walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:#"zancu000%d.png", i]]];
}
CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];
// Create a sprite for our bear
CGSize winSize = [CCDirector sharedDirector].winSize;
self.bear = [CCSprite spriteWithSpriteFrameName:#"zancu0001.png"];
//random position
int minY = _bear.contentSize.width/2;
int maxY = winSize.width - _bear.contentSize.width/2;
int rangeY = maxY - minY;
int actualX = (arc4random() % rangeY) + minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
_bear.position = ccp(actualX,winSize.height + (_bear.contentSize.height/2));
self.walkAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
//animation
[spriteSheet addChild:_bear];
//∫aqui pasar un for para poder saber que position es
CCLOG(#"cantidad de zancudos%d",zan);
[_targets insertObject:_bear atIndex:zan];
i have deleted a mutable _target for index- i have a selector update. try delete a mutablearray this.
for (CCSprite *target in targetsToDelete) {
if (_targets.count!=0) {
for (int j=1; j==_targets.count; j++) {
[_targets removeObjectAtIndex:j];
}
}
I need help
use syntax like this for crash free delete;
NSArray *array = [NSArray arrayWithArray: _targets];
for(CCSprite *sprite in array)
{
if(sprite.tag == kToDelete) //mark somewhere in game :or use ur logic here
{
[_targets removeObject: sprite];
[sprite stopAllActions];
[sprite removeFromParentAndCleanup:YES];
}
}
Your loop will try and access an index out of the array's bounds...try this
for (int j = 0; j == _targets.count - 1; j++)
{
[_targets removeObjectAtIndex:j];
}
However, since it appears you are only removing the last element of the array with this code, you could skip the for loop and use:
[_targets removeLastObject];
The moment you remove an object from _targets, the effective count actually changes. So if you start the loop with a count of 10, and eventually the value of j will be out of bounds. I dont follow quite well the logic of your if ( the == ), but if you are trying to remove all objects, instead of the loop :
[_targets removeAllObjects];

Countdown timer in cocos2d?

I'm trying to create a countdown timer in cocos2d, but I can not help and would like to resolve this problem, my code is below this, perhaps the logic is wrong but I can not fix.
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init] )) {
CCSprite *background = [CCSprite spriteWithFile:#"backgame.png"];
CGSize size = [[CCDirector sharedDirector] winSize];
[background setPosition:ccp(size.width/2, size.height/2)];
[self addChild: background];
[self schedule:#selector(countDown:)];
}
return self;
}
-(void)countDown:(ccTime)delta
{
CCLabel *text = [CCLabel labelWithString:#" "
fontName:#"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:text];
int countTime = 20;
while (countTime != 0) {
countTime -= 1;
[text setString:[NSString stringWithFormat:#"%i", countTime]];
}
}
Your int countTime = 20; is declaring itself every time to be 20. Also, your while loop will decrement the countTimer as fast as the system can update the CCLabel. If you're trying to do a real timer, you want it to decrement ONLY when countDown: is called. Not during a while-loop.
Try this:
#interface MyScene : CCLayer
{
CCLabel *_text;
}
#property (nonatomic, retain) int countTime;
#end
#implementation MyScene
#synthesize countTime = _countTime;
-(id) init {
if( (self=[super init] )) {
CCSprite *background = [CCSprite spriteWithFile:#"backgame.png"];
CGSize size = [[CCDirector sharedDirector] winSize];
[background setPosition:ccp(size.width/2, size.height/2)];
[self addChild: background];
_countTime = 20;
_text = [CCLabel labelWithString:[NSString stringWithFormat:#"%i", self.countTime]
fontName:#"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:_text];
[self schedule:#selector(countDown:) interval:0.5f];// 0.5second intervals
}
return self;
}
-(void)countDown:(ccTime)delta {
self.countTime--;
[_text setString:[NSString stringWithFormat:#"%i", self.countTime]];
if (self.countTime <= 0) {
[self unschedule:#selector(countDown:)];
}
}
#end
Your count allways becomes 20 in your countDown.
You should also move this to your init:
CCLabel *text = [CCLabel labelWithString:#" "
fontName:#"BallsoOnTheRampage" fontSize:46];
text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:text];
Then you should use:
[self schedule:#selector(countDown:) interval:1.0f];
Then instead of using CCLabel you should use CCLabelBMFont. It's much faster :)