Reputation: 171
I created a really simple game in xcode using spritekit and swift. Now I want to have a main menu that shows up when I first start the app. Then i want to have a button that when tapped on, will start the game. Is there a way to do this? Should i be using story board? thanks so much! :)
Upvotes: 2
Views: 4908
Reputation: 5198
Alternatively, you can use Storyboards. In the M.W.E. for another S.O. question they have a basic "menu" set up.
In your case, what you would do is:
Images
Upvotes: 0
Reputation: 71854
By using SpriteKit
you can do it this way:
In your GameViewController.swift
replace your code with this code:
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//load your GameScene from viewController
let scene = GameScene(size: view.bounds.size)
let skView = view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = true
scene.scaleMode = .ResizeFill
skView.presentScene(scene)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
This code will load GameScene
when you start your game.
Add this code in your GameScene.swift
class:
import SpriteKit
class GameScene: SKScene {
//create playbutton instance
let playButton = SKSpriteNode(imageNamed: "play_unpresed")
override func didMoveToView(view: SKView) {
backgroundColor = UIColor.greenColor()
addPlayButton() //add playbutton
}
func addPlayButton(){
playButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
playButton.xScale = 0.2
playButton.yScale = 0.2
self.addChild(playButton)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>){
let location = touch.locationInNode(self)
//this will detect touch on play button
if self.nodeAtPoint(location) == self.playButton {
//it will transits to the next scene
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let letsPlay = playScene(size: self.size)
self.view?.presentScene(letsPlay, transition: reveal)
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
This will load a scene with one button now when you press a button it will take you to your playScene
And for that you have to create a new file by clicking Command + N then iOS Source -> Cocoa Touch class -> next -> add class name playScene -> Subclass of SKScene -> and create it.
Add import SpriteKit
in your playScene.swift
Check THIS sample project for more info.
And HERE is the easy tutorial for spriteKit.
Upvotes: 1
Reputation: 1611
You can just drag one viewController to the storyBoard.
set it Is Initial View Controller
, add one button on it
control+drag
from the button to your Game View Controller. choose show
I've test it. It can work. When I click the button, It will navigate to the Game view controller
Upvotes: 0