0
votes

In my GameScene.sks I have a SKSpriteNode which represents a "ball".

I need to subclass SKSpriteNode as Ball:

class Ball:SKSpriteNode {
    //custom init
} 

In my scene, I would like init my Ball using the SKSpriteNode in the .sks.

As I'm using Xcode 8, I tried to use the custom class in my SKSpriteNode:

enter image description here

self.ball = self.childNode(withName: "ball") as! Ball

But my app crashes at this line... Also I'm not sure how to create a custom initializer for my subclass.

FYI I would prefer to avoid having something like:

class Ball:SKNode {
    var sprite:SKSpriteNode!
}

let ball = Ball()
ball.sprite = self.childNode(withName: "ball") as? SKSpriteNode
1
Why are you casting a Ball to a Puck?Luca Angeletti
@appzYourLife just a mistake :)cmii
This is a wonderful example of Apple not explaining how to get something from the SpriteKit Scene Editor into code, and play with it from there. The Scene Editor and the code live in two different worlds, and the bridge between them is made of twine that those that understand have failed to explain.Confused

1 Answers

0
votes

I think the problem here is that you are not assigning a name to the sprite you add in the scene editor.

You could retrieve your sprite searching for type instead that searching for name

Try this

self.ball = self.children.flatMap { $0 as? Ball }.first!