Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

James Brown
James Brown
2,095 Points

How to use 'did begin contact'?

I'm trying to set up a method for when any child node from a SKSpriteNode comes into contact with another child node from the same SKSpriteNode, but I can't get the contact to register i.e. the NSLog doesn't print out even though there are numerous contacts happening. I've tried to make it as simple as possible, but even this doesn't work. Can someone tell me what I'm doing wrong?

  • (void) didBeginContact:(SKPhysicsContact *)contact {

    if ((contact.bodyA.categoryBitMask == contact.bodyB.categoryBitMask)) { NSLog(@"BAM!"); } }

Any help would be very much appreciated :)

You have a period not a dash or plus before your method. I doubt think that's your problem. Someone else with more experience should handle this. Just wanted to make sure that wasn't the problem :)

2 Answers

James Brown
James Brown
2,095 Points

Sorry guys, I had forgotten to add...

    self.physicsWorld.contactDelegate = self;

... to my init method.

Kieran Robinson
Kieran Robinson
9,411 Points

Hi James Brown, I have not done a lot of Sprite Kit development, however the one difference between the code used in the course and your own code is the conditional within the if statement. (you use ==, in the course > is used). Not sure if this helps but here is the code from the course

-(void)didBeginContact:(SKPhysicsContact *)contact { SKPhysicsBody *firstBody, *secondBody; if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) { firstBody = contact.bodyA; secondBody = contact.bodyB; } else { firstBody = contact.bodyB; secondBody = contact.bodyA; }

James Brown
James Brown
2,095 Points

Thanks Kieran, the reason I have == is because I have multiple child nodes from the same SKSpriteNode (rather than a projectile and an enemy) and want to track when they contact each other.