SpriteKit Project — AbsolutelyBrickingIt — Part 4: Add a main menu
In this article, we’ll add a simple main menu scene that will be shown to the user when the app has finished launching.
Adding image assets for the menu
Add the image assets for the menu scene to Assets
:
Creating a new SpriteKit scene
Right click on the project folder and select New File...
:
Save the file as MenuScene
in the main project folder:
Add the code for an empty SpriteKit scene:
import SpriteKit
class MenuScene: SKScene {
override func didMove(to view: SKView) {
}
}
Update GameViewController
to present MenuScene
instead of GameScene
:
let scene = MenuScene(size: CGSize(width: 375.0, height: 667.0))
Initialise a SKSpriteNode
with the background.menu
image. Position it in the center of the scene and add it as a child of the scene:
override func didMove(to view: SKView) {
let backgroundNode = SKSpriteNode(imageNamed: "background.menu")
backgroundNode.position = CGPoint(x: 0.5 * size.width, y: 0.5 * size.height)
addChild(backgroundNode)
}
Run the project in the Simulator to confirm the MenuScene
with its background is presented when the app launches:
Add remaining elements to the scene
Add a SKSpriteNode
for each of the other elements in the scene:
- The logo
- The about button
- The play button
override func didMove(to view: SKView) {
let backgroundNode = SKSpriteNode(imageNamed: "background.menu")
backgroundNode.position = CGPoint(x: 0.5 * size.width, y: 0.5 * size.height)
addChild(backgroundNode)
let logoNode = SKSpriteNode(imageNamed: "logo")
logoNode.position = CGPoint(x: 0.5 * size.width, y: 0.8 * size.height)
addChild(logoNode)
let aboutNode = SKSpriteNode(imageNamed: "button.about")
aboutNode.position = CGPoint(x: 0.5 * size.width, y: 0.32 * size.height)
addChild(aboutNode)
let playNode = SKSpriteNode(imageNamed: "button.play")
playNode.position = CGPoint(x: 0.5 * size.width, y: 0.2 * size.height)
addChild(playNode)
}
Run the app a few times to see a couple of potential issues:
- The logo looks too big on the screen
- Sometimes one or more elements may not be visible:
In GameViewController
set the scene's scaleMode
to .resizeFill
and ignoreSiblingOrder
to false
to fix the issues:
.resizeFill
ensures the scene contents get resized to fill the screenignoreSiblingOrder = false
means that children are rendered in the order they are added. In this case, background is added first, then the logo is added on top of it, and so on.
let scene = MenuScene(size: CGSize(width: 375.0, height: 667.0))
scene.scaleMode = .resizeFill
view.ignoresSiblingOrder = false
Run in the Simulator again to see that the issues have been fixed:
We have now added the menu scene and all its elements. It is displayed when the app is launched instead of the game scene.
Code
This article corresponds to the merge commit Add menu scene (#4)
in the GitHub repository AbsolutelyBrickingIt