Search code examples
iosswiftsprite-kitxcode6.4

Getting custom class property from contact.bodyA.node


I am developing an IOS game and I am having some issue with didBeginContact().

I am trying to get a .difference property from one of my custom classes, "FullBarClass". Here is some code:

func didBeginContact(contact: SKPhysicsContact) {
    var a: SKPhysicsBody
    var b: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask{
        a = contact.bodyA
        b = contact.bodyB
    } else {
        b = contact.bodyA
        a = contact.bodyB
    }

    let bar : FullBarClass = contact.bodyA.node
    let dif = Int(bar.difference)
    println(dif)
}

On the "let bar : ..." line, I am getting an error: "SKNode? is not convertible to 'FullBarClass' ".

Does anybody know why this is not working?


Solution

  • Since contact.bodyA.node is an optional and may not be a FullBarClass, you can't simply assign the body node object to a FullBarClass constant. You can conditionally assign the object to bar if it's the appropriate type by

    if let bar = contact.bodyA.node as? FullBarClass {
       // This will only execute if body node is a FullBarClass
       let dif = Int(bar.difference)
       print(dif)
    }