1

I have a class named Ball who extends SKSpriteNode class:

import SpriteKit

class Ball: SKSpriteNode {

    var score: Int = 0

    init([...]){
        [...]
    }

    func setScore(score: Int){
        self.score = score;
    }

}

In my GameScene, I detect collisions on my element :

func didBegin(_ contact: SKPhysicsContact) {
    [...]

    // Here I want to call my function in Ball class, but I can't.
    contact.bodyA.node!.setPoints(2);

    [...]
}

How can I call setScore() in didBegin() from contact variable?

Thanks

Swifted
  • 13
  • 2

2 Answers2

1

You need to convert the SKNode of the contact to be your custom Ball. There is also no guarantee that bodyA will be your Ball node, therefore you need to cater for both contact bodyA and bodyB.

 if let ballNode = contact.bodyA.node as? Ball ?? contact.bodyB.node as? Ball {
    ballNode.setPoints(2)
  }
JohnL
  • 570
  • 1
  • 5
  • 10
0

Try to convert body.node to your custom type.

func didBegin(_ contact: SKPhysicsContact) {
    [...]

    // Try to convert body.node to your custom type
    guard let ball = contact.bodyA.node as? Ball else { return }
    ball.setPoints(2);

    [...]
}

Do you know that the didBegin method can be called twice for the same collision (This is called the ghost collision)?

Carrione
  • 55
  • 1
  • 5