1
votes

I'm going through a tutorial/class making a game in Sprite Kit and I'm having issues with multiple collisions happening at the same time.

I'm implementing the didBeginContact: method for all collisions which make the ball bounce because there seems to be a known issue where objects may "stick" to a body if the velocity is too low and angle is too narrow.

By making _ball.physicsBody.collisionBitMask = 0;

and putting the below line in the didBeginContact

if(other body == firstbody && _ball == secondbody)
secondBody.velocity = (CGVectorMake(secondBody.velocity.dx * -1.0, secondBody.velocity.dy));

(or dy * -1.0 for vertical collisions)

I can make the object bounce naturally and it works.

The issue I'm having is when there multiple contacts are called on the _ball. If 1 collision makes the _ball reverse its direction and it hits another object of the same type which reverses direction again, the _ball will continue moving in it's original direction (Double Negative). The _ball just moves through these objects. I can make it bounce back if I secondBody.categoryBitMask = 0; but i then i have the issue of returning the _ball to it's original category.

Does anyone know if you an cycle through contacts or stop contacts on a body after it processes a contact once?

Any thoughts?

1
"I'm calling the didBeginContact: method" <-- you're not supposed to call that method yourself, it is sent by the framework whenever two bodies collide.LearnCocos2D
sorry not "calling" I meant implemented.user3277892

1 Answers

0
votes

I had many problems with correct amount of collisions. Sometimes it would get one, sometimes none. So I tried this and it works. The only thing to change is in didBeginContact method.

I will presume that you declared categories like that you correctly implemented physics delegate. So:

//define collision categories on the top of implementation file
static const uint32_t category1    = 0x1 << 0;
static const uint32_t category2    = 0x1 << 1;
static const uint32_t category3    = 0x1 << 2;

Try to replace your code in didBeginContact with this one. I remember that correct collisions finally got to work after I did this.

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

   SKNode *newFirstBody = contact.bodyA.node;
   SKNode *newSecondBody = contact.bodyB.node;

  uint32_t collision = newFirstBody.physicsBody.categoryBitMask |  newSecondBody.physicsBody.categoryBitMask;

 if (collision == (category1 | category2))
{
    NSLog(@"hit");
}

 }

Hope it helps