cocos2d-iphone: init method does not work properly - cocos2d-iphone

I'm studying Strougo/Wenderlich tutorial (space Viking project). I got troubles with chapter 4.
In RadarDish.m:
-(void)initAnimations
{
[self setTransmittingAnim: [self loadPlistForAnimationWithName:#"transmittingAnim" andClassName:NSStringFromClass([self class])]];
}
-(void)changeState:(CharacterStates)newState {
[self stopAllActions];
id action = nil;
[self setCharacterState:newState];
switch (newState) {
.
.
case kStateIdle:
action = [CCAnimate actionWithAnimation:transmittingAnim
restoreOriginalFrame:NO];
break; }
if (action != nil) {
[self runAction:action];
}
}
-(id)init
{
self=[super init];
if (self!=nil) {
.
.
[self initAnimations];
.
.
}
return self;
}
Exact the same code as in the tutorial. Failure:
*** Assertion failure in -[CCAnimate initWithAnimation:], /Users/macowner/Documents/examples/SpaceViking/SpaceViking/libs/cocos2d/CCActionInterval.
Using debugger with breakpoints, i noticed that value of transmittingAnim = nil.
So, if i put line with
[self setTransmittingAnim:
[self loadPlistForAnimationWithName:#"transmittingAnim" andClassName:NSStringFromClass([self class])]];
into case of
-(void)changeState then animation works correctly.
Why [self initAnimations] from (id)init is not called?
Im using cocos2d v.2 templates.
Great thanks in advance.

I had problems because I have been building project using cocos 2d v.2.0, while tutorial is based on cocos 2d templates v.1.x.x If you are going to follow the book "Learning Cocos2D", I strongly recommend you loading cocos2d-iphone version 1.0.1. Here is the link download cocos2d 1.x.x branch
if you still want to use latest cocos2d templates, I can give you some advice:
Follow the instructions in this link cocos2d v2.0 migration guide
You are going to have a lot of deprecations and changes to fix, so use this link to understand how to fix those deprecations and changes.
Now few words about the solution of the problem I mentioned here. In each of the GameObjects, EnemyObjects, and PowerUps, I added a method to override initWithFrameName.
-(id) initWithSpriteFrameName:(NSString*)frameName{
if ((self=[super init])) {
if ((self = [super initWithSpriteFrameName:frameName])) {
CCLOG(#"### RadarDish initialized");
[self initAnimations]; // 1
characterHealth = 100.0f; // 2
gameObjectType = kEnemyTypeRadarDish; // 3
[self changeState:kStateSpawning]; // 4
}
}
return self;
}
    This allows the GameObject and GameCharacter init methods to run before the CCSprite's initWithSpriteFrameName method to run.
    
    The Viking GameObject had to have a slightly different solution because it is initialized with initWithSpriteFrame rather than initWithSpriteFrameName. However, the override implementation is basically the same as the example of RadarDish above.

Related

Cocos2d. My app crashes in -(void) update:(ccTime)delta method when I use a pre-existing NSMutableArray in a different method -(void)InitCats

guys! Sorry for my bad language.
My app crashes in Update method when I use array which I created in different method InitCats. I create NSMutableArray* Cats and CCSprite* CA in header file in #interface { }.
-(id)init
{
[self InitCats];
[self schedule:#selector(update:) interval:0.0f];
}
-(void)InitCats // This method is work well in -(id)init
{
Cats = [NSMutableArray arrayWithCapacity:NumCats];
for (int a=0; a<NumCats; a++)
{
CCSprite* Cat=[CCSprite spriteWithFile:#"1.png"];
[Cats addObject:Cat];
}
}
-(void) update:(ccTime)delta
{
for (int a=0; a<NumCats; a++)
{
CA = [Cats objectAtIndex:a]; //In this place I have ERROR, app crashes
CA.position = CGPointMake(CA.position.x-1, CA.position.y);
}
}
I guess you pointing to released object. try initialize your array
Cats = [[NSMutableArray alloc] initWithCapacity:NumCats];
and on dealloc
-(void)dealloc
{
[Cats release];
[super dealloc];
}
Ok, the issue is this statement:
Cats = [NSMutableArray arrayWithCapacity:NumCats];
Which will create an auto-released object, however the pointer to this object will be non-nil after it's auto-released, and hence your code is referencing a deallocated object.
You already have a fix:
Cats = [[NSMutableArray alloc] initWithCapacity:NumCats];
and remove the arrayWithCapacity call from within the InitCats method.
(note your capitalization of method and instance variable names is unconventional).

run another animation after running an animation with ccbanimationmanager

I'm running cocos2d with cocosbuilder 2.1 and I use the cocosbuilder animation delegate (CCBAnimationManagerDelegate::completedAnimationSequenceNamed) to get notified when an animation has completed and take actions like firing another cocosbuilder animation.
It runs fine the first time the foodfactoryshow animation is run from the delegate and after the animation is completed it also runs restoration animation correctly. However, when restoration animation is completed, the parameter name for -(void) completedAnimationSequenceNamed method is NULL!?
-(void) completedAnimationSequenceNamed:(NSString*)name
{
if ([name isEqualToString:#"foodfactoryshow"])
{
[manager runAnimationsForSequenceNamed:#"restoration"];
}
if ([name isEqualToString:#"restoration"])
{
[self colorLayerChanged];
self.gameLayer.isLock = true;
}
}
Is this a bug or am I not supposed to run animations from the CCBAnimationManagerDelegate::completedAnimationSequenceNamed method!?
Thanks in advance for your help.
I believe it is a CCBReader bug. There is an open issue about it in the CocosBuilder github page (https://github.com/cocos2d/CocosBuilder/issues/121). It should be fixed in the latest version of CocosBuilder + CCBReader, however, if you want to use the 2.1 version you can change the "sequenceCompleted" method of CCBAnimationManager to the following:
- (void) sequenceCompleted
{
NSString *completedSequenceName = [runningSequence.name copy];
int nextSeqId = runningSequence.chainedSequenceId;
runningSequence = NULL;
if (nextSeqId != -1)
{
[self runAnimationsForSequenceId:nextSeqId tweenDuration:0];
}
[delegate completedAnimationSequenceNamed:completedSequenceName];
[completedSequenceName release];
}

nsmutablearray not adding objects when called

I have an NSMutable array that I want to add Sprites to so that I can check them if they've hit the wall. I use this code to do so:
NSString *bulletName = [NSString stringWithFormat:#"tank%d_bullet.png", _type];
bullet = [CCSprite spriteWithSpriteFrameName:bulletName];
bullet.tag = _type;
bullet.position = ccpAdd(self.position, ccpMult(_shootVector, _turret.contentSize.height));
CCMoveBy * move = [CCMoveBy actionWithDuration:duration position:actualVector];
CCCallBlockN * call = [CCCallBlockN actionWithBlock:^(CCNode *node) {
[node removeFromParentAndCleanup:YES];
}];
if (!bulletIsGone) {
[self schedule:#selector(updator:) interval:0.01];
}
else {
[self unschedule:#selector(updator:)];
}
[bullet runAction:[CCSequence actions:move, call, nil]];
[_layer.batchNode addChild:bullet];
[bulletsArray addObject:bullet];
if ([bulletsArray objectAtIndex:0] == nil) {
NSLog(#"HELP");
}
NSLog(#"%#", [bulletsArray objectAtIndex:0]);
}
-(void)updator: (ccTime) dt{
for(CCSprite *bulletz in bulletsArray){
NSLog(#"this is the for loop");
CGRect rect1 = CGRectMake(bulletz.position.x - bulletz.contentSize.width/2, bulletz.position.y - bulletz.contentSize.height/2, 20, 20);
if ([_layer isWallAtRect:rect1]) {
NSLog(#"bulletHitWall");
[_layer.batchNode removeChild:bulletz cleanup:NO];
bulletIsGone = YES;
}
}
}
However, when I build and run, I get the console output of '(null)' and 'HELP.' The method before the 'updator' is called from touchesEnded. Can someone see what I'm doing wrong?
Thank you!
Do you initialise the array? That would seem like the most likely reason
Try this in your viewDidLoad method...
- (void)viewDidLoad
{
[super viewDidLoad];
bulletsArray = [NSMutableArray alloc] init];
}
Since NSMutableArray cannot hold nil objects, the only way the condition
[bulletsArray objectAtIndex:0] == nil
could evaluate to true is that bulletsArray is nil. You need to make sure that the array is properly allocated. A typical place to do it is the designated initializer of your class.
Why do you want to add bullets to another array? You already have a batch node that contains them all which is _layer.children.
Are you sure that the array itself (bulletsArray) is not nil? where is it initialized?
Finally you should consider looping with CCARRAY_FOREACH which is more performant.

Callback when Cocos2d CCParticleSystem has finished?

I'd like to run a callback/selector when a Cocos2d CCParticleExplosion is completely finished. How do I do this?
I tried using scheduleOnce with the same duration as the emitter, but that finish too soon since I guess the duration of the emitter controls for how long it will emit new particles, but not how long the complete animation lasts.
Try sequencing the action (using CCSequence) with a CCCAllFunc Action. After one action runs, the other runs, the CCCAllFunc can be assigned to the selector/method of your choice.
Not sure if this is acceptable, but I tested and "it works on my mac".
in CCParticleSystem.h
// experimental
typedef void (^onCompletedBlock)();
#property (readwrite, copy) onCompletedBlock onComplete;
in CCParticleSystem.m
#synthesize onComplete;
in the same file update method,
_particleCount--;
if( _particleCount == 0 && self.onComplete)
{
[self onComplete]();
[[self onComplete] release];
}
if( _particleCount == 0 && _autoRemoveOnFinish ) {
[self unscheduleUpdate];
[_parent removeChild:self cleanup:YES];
return;
}
In your code
particleSystem.autoRemoveOnFinish = YES;
particleSystem.position = ccp(screenSize.width/2, screenSize.height/4);
particleSystem.onComplete = ^
{
NSLog(#"completed ..");
};
again, quite experimental..

CCLabelAtlas setString doesn't update label

I have a CCLabelAtlas that I have on a layer to display the current score within my game...the problem that I am having with it is that it does not update when I use [scoreLabel setString:]. Here's how I have it laid out:
In the header:
#interface GameScene : CCLayer {
...
CCLabelAtlas* scoreLabel;
}
And in the init:
scoreLabel = [[CCLabelAtlas alloc] initWithString:#"0" charMapFile:#"scoreCharMap.png" itemWidth:6 itemHeight:8 startCharMap:'.'];
[scoreLabel setPosition:ccp(105, 414)];
[self addChild:scoreLabel z: 6];
scoreCharMap.png is a custom map that includes ./0123456789 of my desired font. When the score is changed, I attempt to do this to get the label to update with the current score:
NSString* str = [[NSString alloc] initWithFormat:#"%d", [[GameRunner sharedInstance] currentScore]];
[scoreLabel setString: str];
[str release];
[scoreLabel draw];
Problem is that it doesn't ever update - it just sits there and displays 0. I know for a fact due to breakpoints and debugging that setString is being called, and that the string that it should be displaying is correct - but it just doesn't update. Hard-coding the value and saying [scoreLabel setString:#"1234"] does nothing, either. What am I doing wrong here? I am using Cocos2d 0.99 - thanks in advance!
Maybe this is something wrong with the font you are using? Try using one of the font maps that came with Cocos2D and see if it works for you.
The method -[CCLabelAtlas setString:] does a few things.
Can you verify that following goes right: (place a breakpoint and step through the function)
resizeCapacity doesn't fail to resize
updateAtlasvalues retreives a UTF8 character array pointer. Inspect that to see if that's the correct string, and while you're there, inspect n in the same method, which should be your string length
See code for setString below:
- (void) setString:(NSString*) newString {
if( newString.length > textureAtlas_.totalQuads )
[textureAtlas_ resizeCapacity: newString.length];
[string_ release];
string_ = [newString retain];
[self updateAtlasValues];
CGSize s;
s.width = [string_ length] * itemWidth;
s.height = itemHeight;
[self setContentSize:s];
}
Let me know what the results are, if you still need any help.