mdamkani
mdamkani

Reputation: 305

Swift: Spritekit: Switching Scenes (anchor point?)

I have two scenes I want to swap between. On each scene there is a button that swaps to the other scene, and I would like the button to be in the middle of the screen. For the first scene this works (I put the button at 0,0). But for the second scene, the anchor point of 0,0 is at bottom left instead of at center.. and strangely, when moving back to the first scene, the button appears at button left, even though it was centered before!

here is the code (code is identical for both scenes, other than scene names)

class LevelGeneral: SKScene {
    var buttonplay = SKSpriteNode()

    override func didMove(to view: SKView) {

        buttonplay = SKSpriteNode(imageNamed: "button1")
        buttonplay.size = CGSize(width: self.frame.width/2, height: self.frame.height/8)
        buttonplay.position = CGPoint(x: 0, y: 0)
        self.addChild(buttonplay)

    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: self)
            if buttonplay.contains(location) {
                let nextScene = GameScene(size: self.size)
                let reveal = SKTransition.fade(withDuration: 0.1)
                self.view?.presentScene(nextScene,transition: reveal)
            }
        }
    }
}

if I change the button position to be screenwidth/2, screenheight/2 (in both scenes), the button will appear at the top right corner at first, and centered thereafter. any help would be appreciated

Upvotes: 0

Views: 593

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

This is because LevelGeneral is made with an SKS file with default anchor point of 0.5,0.5 and "GameScene" is made via code of size self.size with an anchor point of 0.0, 0.0. You should try and stay consistent with how you load scenes.

Personally, you should get used to the mentality of separating design from function. Build how everything looks in the SpriteKit Editor, and you will never have to guess why things are not appearing where they should be (Unless some function is causing it not to appear where it should be)

Upvotes: 1

Related Questions