I'm making a game with many bodies of different categories. When the user moves one body and collide it with another one of the same category they glue to each other. When three bodies are glued in total, they disappear.
Bodies have a bit mask for it's specific category and a CNPhysicsCategoryGenBody identifying a body in general. This is a game requirement because there are other bodies that participate in the collision that are not controlled by the user and don't glue to each other.
Code of the didBeginContact involved in the bodies to glue:
// Here I clean the mask removing the CNPhysicsCategoryGenBody and leaving the object particular
// category only.
uint32_t cleanMaskA = contact.bodyA.categoryBitMask ^ CNPhysicsCategoryGenBody;
uint32_t cleanMaskB = contact.bodyB.categoryBitMask ^ CNPhysicsCategoryGenBody;
// If the objects are of the same category create a joint
if (cleanMaskA == cleanMaskB) {
SKPhysicsJointFixed *newJoint = [SKPhysicsJointFixed jointWithBodyA:contact.bodyA bodyB:contact.bodyB anchor:contact.contactPoint];
[self.physicsWorld addJoint:newJoint];
}
So far so good. The problem comes when I want to list the bodies that are attached to another one. The SKPhysicsBody -allContactedBodies method doesn't return the bodies in a joint. I think that's probably because the body is attached to a joint and not to another body.
The SKPhysicsWorld has methods to add or remove joints but I can't find a way to list the bodies that participate in a joint. I need to list these bodies in order to check which bodies are glued, see if they are more than a certain number and remove them.
The
allContactedBodies
method will indeed not return the bodies participating in a joint.To list the bodies participating in a joint, you have two out-of-the-box options:
1) the
newJoint.bodyA.node
andnewJoint.bodyB.node
getters will return the 2 bodies in each joint2) better yet, go the other way round - enumerate through your all your nodes' bodies and use the
physicsBody.joints
property - this will return an array of the joints this body is connected to, then compare the joints to get actual groups of glued bodies.