user3423384
user3423384

Reputation: 697

Double notification on contact in spriteKit

I seem to get a double notification when my SKSpriteNode hits has contact with the worldCategory, how come is this? This creates problem when i want to run an action when it touches the worldCategory, since the action is being triggered

Here is my bitmask in the InitWithSize method

    mover.physicsBody.categoryBitMask = birdCategory;
    bottom.physicsBody.categoryBitMask = worldCategory;

    mover.physicsBody.contactTestBitMask = worldCategory;

and here is the contact method:

- (void)didBeginContact:(SKPhysicsContact *)contact {
if (contact.bodyA.categoryBitMask == worldCategory) {



    mover.texture = [SKTexture textureWithImageNamed:@"birddead1"];
    NSLog(@"Contact");





    self.scene.paused = YES;
    [pauseButton removeFromSuperview];



}
}

In my log there is being shown two lines with "Contact"

Upvotes: 1

Views: 170

Answers (2)

sangony
sangony

Reputation: 11696

Set your object's restitution property to zero like this:

self.physicsBody.restitution = 0;  //it's either self or the name of your object

If that does not solve your issue, look at the movement code related to your object(s). Look for any situation that cause a 'back and forth' movement which can create the double contact issue.

As a last resort you can set up a filter for your contacts:

  1. Create a variable which stores the time a contact was made.
  2. Compare the contact variable time against the current time in the update: method.
  3. If the difference is less than your specified time (example 0.2 sec) then allow the contact and set your contact time variable to the current time. If the difference is below the filter time (0.2 sec), ignore the contact.

Upvotes: 1

adimona
adimona

Reputation: 127

I think you can try to be more specific about which body is A and which is B and which hits what. Maybe something like this:

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

                SKSpriteNode *firstNode, *secondNode;
                firstNode = (SKSpriteNode *)contact.bodyA.node;
                secondNode = (SKSpriteNode *) contact.bodyB.node;
                int bodyAA = contact.bodyA.categoryBitMask;
                int bodyBB = contact.bodyB.categoryBitMask;


       if ((bodyAA == birdCategory && (bodyBB == worldCategory)){

               mover.texture = [SKTexture textureWithImageNamed:@"birddead1"];
               NSLog(@"Contact");
               self.scene.paused = YES;
               [pauseButton removeFromSuperview];

        }
}

If you are using iOS 7.1 you may want to also set the skView.showsPhysics to YES at ViewController.m this way you can clearly see what is happening.

Upvotes: 0

Related Questions