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