Alter SKReferenceNode from GameViewController

77 views Asked by At

I'm developing a game in Swift using the SpriteKit framework. In this app, I have GameScene.sks where my UI is presented. Within that .sks file there is an SKReferenceNode for the bottom-menu. The bottom-menu is going to change it's height if the user is running the game from an iPhone X.

However, I have some trouble getting to that point. I made the menu a SKReferenceNode because it's used in multiple scenes - so if I change the menu, it will change in all of the scenes (GameScene.sks, GameScene1.sks, GameScene2.sks and so on.. )

What would be the best way to approach this? I'm sorry if this is an obvious question, but I've been starring myself blind at this one.

1

There are 1 answers

4
Ron Myschuk On BEST ANSWER

you are doing fine, using menu as an SKReferenceNode is what I would do as well. However you don't need to alter it from the GameViewController to achieve the results you want.

What I do in the situation where I need the appearance of an RefNode to be dependant on some variables I don't load the appearance in the required init

normally inside of the RefNode class I do this

class SomeObject: SKSpriteNode {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    func setup() {
        //setup objects in here
    }
}

but instead when i need to alter the presentation i comment out the setup call in the required init

and then call setup from the initialization code in my GameScene

class SomeObject: SKSpriteNode {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)    
        //setup()
    }

    func setup(height: CGFloat) {

        //setup objects in here
        if let background = self.childNode(withName: "//background") as? SKSpriteNode {
            self. background = background
            background.size.height = height
        }
    }
}

then in GameScene

func createSomeObject() {

    if let someObjectNode = self.childNode(withName: "//someObjectNode") as? SKReferenceNode {

        someObject = someObjectNode(withName: "//someObjectNode") as? SomeObject

        //you can figure out this multiple ways
        if isIpad {
            height = 50
        }
        else if isIphoneX {
            height = 250
        }
        someObject.setup(height: height)
    }
}