1
\$\begingroup\$

I'm working on a tvOS game that uses the siri gamepad controller. Everything works fine the first time out. If the user loses the round I reload the same scene using presentScene. After reloading the scene any reference to self.xxxxx don't work in the valuechangehandler closure because the it references the first scene not the new one.

In my didMoveToView there is the usual

NSNotificationCenter.defaultCenter().addObserver(self,
        selector: Selector("gameControllerDidConnect:"),
        name: GCControllerDidConnectNotification,
        object: nil)

In the gameControllerDidConnect function we have:

if let controller = notification.object as? GCController {

        if let mGPad = controller.microGamepad {

            let gamePad = mGPad
            gamePad.allowsRotation = true
            gamePad.reportsAbsoluteDpadValues = true

            gamePad.buttonA.valueChangedHandler = { (buttonA: GCControllerButtonInput, value:Float, pressed:Bool) -> Void in

                    print("buttonA")        // <--- this still works
                self.theBall.alpha = 0.5    // <--- this does not

            }}}

Since the observer is added every time the scene is loaded should this not reflect in the self reference to the scene being updated?

Out of sheer desperation I filed a bug report with apple and this is the answer they gave:

When "reloading" the scene, the scene instance is recreated. The old value changed handler for the controller references the ball object in a SKScene instance where it is garbage collected. You need to re-register value changed handler for the controller whenever the scene is reloaded.

So if the addObserver doesn't do this every time then how do I do this inside the didMoveToView method? My apologies if this is a really dumb question. I'm migrating from a lua based SDK to spritekit/swift.

\$\endgroup\$
0
\$\begingroup\$

Well, I finally found a tutorial here: [link]http://cartoonsmart.com/how-to-support-external-game-controllers-with-swift-2-and-sprite-kit-for-the-new-apple-tv/ that addressed how to get around the issue. The trick is to extend the gamescene class and place the listener functions in the extension. These then get called at the start of didMoveToView everytime the scene is loaded.

\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.