How to know which SKSpriteNode is affected by collision detection in Swift?

前端 未结 1 1009
旧时难觅i
旧时难觅i 2021-01-03 04:01

Situation: I have two or more ships on my iOS screen. Both have different attributes like name, size, hitpoints and score points. They are displayed as

相关标签:
1条回答
  • 2021-01-03 04:18

    The SKPhysicsBody has a property node which is the SKNode associated to the body. You just need to perform a conditional cast to your Ship class.

        if let ship = contact.bodyA.node as? Ship {
            // here you have your ship object of type Ship
            print("Score of this ship is: \(ship.score)!!!")
        }
    

    Please note that the Ship node could be the one associated with bodyB so.

        if let ship = contact.bodyA.node as? Ship {
            // here you have your ship...
        } else if let ship = contact.bodyB.node as? Ship {
            // here you have your ship...
        }
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题