1

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?

rene
  • 41,474
  • 78
  • 114
  • 152
Daniel
  • 3,188
  • 14
  • 34

1 Answers1

2

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)
}
0x141E
  • 12,613
  • 2
  • 41
  • 54