How to create a main menu for a spritekit game made with swift in xcode?

12,436

Solution 1

Swift 3.0

import SpriteKit

class MenuScene: SKScene {

    var playButton = SKSpriteNode()
    let playButtonTex = SKTexture(imageNamed: "play")

    override func didMove(to view: SKView) {

        playButton = SKSpriteNode(texture: playButtonTex)
        playButton.position = CGPoint(x: frame.midX, y: frame.midY)
        self.addChild(playButton)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let pos = touch.location(in: self)
            let node = self.atPoint(pos)

            if node == playButton {
                if let view = view {
                    let transition:SKTransition = SKTransition.fade(withDuration: 1)
                    let scene:SKScene = GameScene(size: self.size)
                    self.view?.presentScene(scene, transition: transition)
                }
            }
        }
    }
}

Solution 2

Create two new files. One sprite kit scene and one cocoa touch file. Name them the same so for example MenuScene. To create the files you click on the folder in the sidebar of your xcode project. Then to have the MenuScene show when you run your app go into the GameViewController file. There is a line under viewDidLoad. if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { change this into if let scene = MenuScene.unarchiveFromFile("MenuScene") as? Menu Scene { Then in your MenuScene you have to have a button that leads you to your GameScene

import SpriteKit

class MenuScene: SKScene {

var playButton = SKSpriteNode()
let playButtonTex = SKTexture(imageNamed: "play")

override func didMoveToView(view: SKView) {

    playButton = SKSpriteNode(texture: playButtonTex)
    playButton.position = CGPointMake(frame.MidX, frame.midY)
    self.addChild(playButton)


override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {


    if let touch = touches.first as? UITouch {
        let pos = touch.locationInNode(self)
        let node = self.nodeAtPoint(pos)

        if node == playButton {
            if let view = view {
                let scene = GameScene.unarchiveFromFile("GameScene") as! GameScene
                scene.scaleMode = SKSceneScaleMode.AspectFill
                view.presentScene(scene)   
            }   
        }   
    }       
}

Ask If you need further explanation.

Share:
12,436
King_Cui
Author by

King_Cui

Updated on July 18, 2022

Comments

  • King_Cui
    King_Cui almost 2 years

    I created a really simple game in xcode using spritekit and swift. I have finished coding the actual game itself. Now I want to create a main menu so that when the game opens, there will be a menu with buttons either going into settings or starting the game. I have no idea how I can do this. Should I use storyboard? And if so, how can i implement it in xcode. Thanks everyone :)