Search code examples
swiftsprite-kitskphysicsbody

How to detect the collision nodes name in skspritekit?


I would like to detect the nodes name my player node colides with. Is that possible?

func didBegin(_ contact: SKPhysicsContact) {
    
    let collision: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
    
    for i in CollectionObject {
        if collision == Player.physicsBody!.categoryBitMask | i.physicsBody!.categoryBitMask{
            print("hit the object") //here I would like to print the nodes name                
        }
    }
}

Solution

  • You can use

    contact.bodyA.node?.name
    

    and

    contact.bodyB.node?.name
    

    to get the names of the 2 nodes colliding with each other.

    So if your player node has a name, then you could use something like the below:

    if contact.bodyA.node?.name == "PlayerName"  {
        print(contact.bodyB.node?.name)
    } else if contact.bodyB.node?.name == "PlayerName" {
        print(contact.bodyA.node?.name)
    }