Search code examples
swiftskphysicsbodycollision

3 different collision bodies? Swift3 + Spritekit


Okay I've searched around and I cannot find an answer to this problem. I have 3 different node types that I want to handle collisions with. A meteor, a shot, and a station. I have the code for the collision handling between the shots and the meteors working perfectly, but I cannot for the life of me figure out how to respond to collisions (yes the collision is being detected but the response code isn't executing) between the station and a meteor. Here's my didBegin func:

func didBegin(_ contact: SKPhysicsContact){
    print("contact")
    let shot = (contact.bodyA.categoryBitMask == shotCategory) ? contact.bodyA : contact.bodyB
    let stationBody = (contact.bodyA.categoryBitMask == stationCategory) ? contact.bodyA : contact.bodyB
    let otherObject = (shot == contact.bodyA) ? contact.bodyB : contact.bodyA

    if ((contact.bodyA == stationBody) && (contact.bodyB == otherObject)) {
        print("collision!")
    }
}

"contact" is being printed when a meteor collides with the station, but "collision!" is not being printed. I know its got something to do with the way the code is worded but i can't seem to get it to work no matter how I write/rewrite it


Solution

  • Try considering the order...

     if (contact.bodyA == stationBody && contact.bodyB == otherObject) || (contact.bodyB == stationBody && contact.bodyA == otherObject)
    

    Also you are setting the other object according to shot, so if shot is not one of the objects in the collision it might be a problem

    if bodyA is the other object and bodyB the station for example, shot would be set to bodyB (because the categoryBitMask != shotCategory) and then the otherObject would be set to bodyA. Therefore contact.bodyB won't equal otherObject.