Search code examples
iosobjective-ccocos2d-iphonecollision-detection

cocos2d collision not detected in if((self=[super init]))


I used a CGRectIntersectsRect to detect the collision of a moving image (anvil) and an image (guy).

The "anvil" moves constantly in a CCRepeatForever and the "guy" moves in a ccTouchesBegan method by the control of the user.

Here it is, very simple:

if (CGRectIntersectsRect(guy.boundingBox, anvil1.boundingBox))
{
      pancake = [CCSprite spriteWithFile:@"pancake.png"];
      pancake.position = ccp(200,200);
      [self addChild:pancake];
}

The problem is that the above lines of code do not work in the if((self=[super init])) and only in the ccTouchesBegan, where I have all of the actions for "guy." I do not want to have the image "pancake" appear only if the user taps exactly when the two images collide...if the images EVER collide, regardless of touch events, "pancake" should appear.

Any advice? Thanks in advance!


Solution

  • Not to criticize but your code doesn't make a lot of sense. Why would you be testing for interestion in an init method for two objects that are constantly in motion throughout your scene? Even if you wanted to show the pancake whenever the two intersected, why don't you load the pancake and make it invisible, then switch it to visible whenever the two objects intersect. This could be done simply by putting the condition in an update method and setting pancake's visible property to true if they intersect or false otherwise.

    But to answer the question of "why" that code doesn't work in init is simply because at the point of calling this either one or both of your objects doesn't exist, they simply don't intersect, or their bounding box properties have not been set. I bet they simply don't intersect yet. But that doesn't matter much since there is no reason I can see to check for interestion in an init method. Schedule the update method, create the update method, and place this condition inside of it but rather than create the pancake sprite, you'd be setting the already existing pancake sprite's visibility to TRUE.