Get class who extends SKSpriteNode in didBegin

48 views Asked by At

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

2

There are 2 answers

0
JohnL On BEST ANSWER

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)
  }
0
Carrione On

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)?