How to create more SKScene in addition to GameScene - ios

I tried to create a new subclass of SKScene "MainScene" like the one apple created the GameScene.
I want to create more scene in addition to my "GameScene" but its not working.
Below is my subclass code.
MainScene :
import SpriteKit
#if !os(iOS)
import AppKit
#endif
class MainScene : SKScene {
override func didMoveToView(view: SKView) {
backgroundColor = UIColor.blueColor()
}
}
MainSceneViewController :
import UIKit
import SpriteKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = MainScene(fileNamed:"MainScene") {
// Configure the view.
let skView = self.view as! SKView
//skView.showsFPS = true
//skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
skView.showsPhysics = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
Error : "Could not cast value of type 'UIView' (0x1097f2b20) to 'SKView' (0x108a4cad0)."

When creating a new scene, you need to actually create a new scene file, not just the code behind file.
To create new scene files, go to file, New, File, then in your sections go to iOS, SpriteKit Scene. This will create the sks file you need.
edit:
In the case you are getting the error Could not cast value of type 'UIView' to 'SKView', this is due to the fact that in your story board, your ViewControllers main view does not have a custom class of SKView. In your storyboard file, open up your view controller, click the view for this controller, make sure the right panel is visible, and select the identity inspector tab (It is probably the 3rd from left, looks like a flag or an envelope with a window). Under Custom Class, look for the class text box, and put in SKView

To create more SKScene in addition to GameScene
Go to New File
Select Coca Touch Class
Click on Next
SubClass : Type Manually SkScene
create
import SpriteKit

Related

SKScene not loaded when add GKComponent to GameScene.sks

I am currently creating a 2D game with Swift SpriteKit and GameplayKit.
I have a GameScene.sks file and a GameScene.swift file that is of type SKScene.
Now I wanted to add a Component of type GKComponent. I created my component and added it to one of my SKSpriteNodes in GameScene.sks
However after adding the Component to the SpriteNode in the Scene Editors Inspector the Scene is no longer loaded and the app shows only a grey screen.
Is this a known issue in XCode?
Is there a way of bypassing this issue?
I have not uploaded any example code. The issue is reproducable by any new XCode Project (ios / Game) that supports SpriteKit and GameplayKit.
Just add a class that is derived from GKComponent and add the class to the given helloLabel in the Scene Editor.
This is how the GameScene is loaded:
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GKScene(fileNamed: "GameScene") {
if let sceneNode = scene.rootNode as! GameScene? {
// This gets only executed when I remove the Component from the SKSpriteNode in the Scene Editor.
}
}
...

SpriteKit Scene referenced with SKReferenceNode does not load custom class

I have a GameScene.sks a custom class GameScene.swift which is connected via the Custom Class Inspector (on the right in Xcode). This is working fine.
Now in the GameScene.swift where I want to reference another scene that I want to reuse in many scenes in the future (oversimplified code):
class GameScene: SKScene {
// ...
override func didMove(to view: SKView) {
//...
guard let gameMenuPath = Bundle.main.path(
forResource: "GameMenu", ofType: "sks") else { return }
let url = NSURL(fileURLWithPath: gameMenuPath) as URL
let gameMenu = SKReferenceNode(url: url)
addChild(gameMenu)
//...
where I am loading a reusable GameMenu.sks.
Everything works fine till here. Now the custom class issue for the GameMenu.sks (the scene to be reused). For the GameMenu.sks I also have a GameMenu.swift which is referenced in the custom class inspector as custom class. So exactly as for the GameScene. The problem is that it seems like the GameMenu.swift is not found/loaded. I get no error - so it looks like I misspelled the custom class - but I checkt it many times and also cleared the Xcode cache.
Any ideas how to set custom class for a scene (.sks) that is referenced in another scene?
I would think this is something that is done for reusable scene parts suche as the GameMenu in my case that is visible in every GameScene.
Thank you for any hints.
Is it necessary to add GameMenu in GameScene via code? You can also simply use the inspector. In your GameScene.sks drop the 'Reference' (SKReferenceNode) object. Select it from the hierarchy and select GameMenu as in the 'reference' dropdown.
SKReferenceNodes behave as nodes, not as scenes, which may cause confusion since you are creating a scene file.
This means none of the functions that a view calls on a scene will be called.
If you need some of these functions to call, you need to do it manually.
Look at this example to get your didMoveToView to fire:
override func didMove(to view: SKView) {
let gameMenu = SKReferenceNode(fileNamed:"GameMenu") as? SKScene // (or your custom class)
addChild(gameMenu)
gameMenu.didMove(to:view)
}

Swift: How to handle view controllers for my game

i have a general question about view controllers and how to handle them in a clean way when i develop a SpriteKit based game.
What i did so far:
Use storyboard only for defining view controllers
SKScene's are presented in each view controller (Home, LevelSelection, Game) by presentScene
in each view controller i call performSegueWithIdentifier with the identifier i defined in the storyboard between the view controllers
all the content i show programmatically using SKSpritenode etc. on the SKScene's
on the storyboard i only have view controllers with segue relations and identifiers defined
all the stuff i do in viewDidDisappear is because it seems to be the only way to get my SKScene deinited correctly
My problems are:
everytime i segue to another view, my memory raises, because the view controller is re-initialized, the old one keeps staying in the stack
it is not clear for me how to handle the segue's between the view controllers, on some tutorial pages i see people using the navigation controller, others are using strong references of some view controllers and using the singleton pattern for the view controller in order to decide either to init the view controller or just show it
my view controllers are not deiniting, i understand my home view can't because it is the initial one, but since ios is reiniting it anyways, why then not unloading it?
What is the correct way for a Swift based game using SpriteKit to handle the view controller? Below you can see my initial view controller (Home) showing an SKScene with a simple play button which calls the play() function to segue to the levelselection
import UIKit
import SpriteKit
class Home : UIViewController {
private var scene : HomeScene!
override func viewDidLoad() {
print(self)
super.viewDidLoad()
self.scene = HomeScene(size: view.bounds.size)
self.scene.scaleMode = .ResizeFill
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(play), name: Constants.Events.Home.play, object: nil)
skView.presentScene(self.scene)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
let v = view as! SKView
self.scene.dispose()
v.presentScene(nil)
NSNotificationCenter.defaultCenter().removeObserver(self)
self.scene = nil
self.view = nil
print("home did disappear")
}
func play() {
self.performSegueWithIdentifier("home_to_levelselection", sender: nil)
}
deinit {
print("Home_VC deinit")
}
}
Your way seems very complicated to essentially present 3 scenes. Its not what you are supposed to do for SpriteKit games, you only really need 1 view controller (GameViewController).
Load your first scene from GameViewController (e.g HomeScene) and nothing else.
Create your playButton and other UI directly in HomeScene. Use SpriteKit APIs for your UI (SKLabelNodes, SKNodes, SKSpriteNodes etc).
You should never really use UIKit (UIButtons, UILabels) in SpriteKit. There are some exceptions to this, like maybe using UICollectionViews for massive level select menus, but basic UI should be done with SpriteKit APIs.
There is plenty tutorials to google on how to create sprite kit buttons, how to use SKLabelNodes etc. Xcode has a SpriteKit level editor so you can do all that visually similar to storyboards.
Than from HomeScene transition to the LevelSelect Scene and than to the GameScene and vice versa. Its super easy to do.
/// Home Scene
class HomeScene: SKScene {
...
func loadLevelSelectScene() {
// Way 1
// code only, no XCode/SpriteKit visual level editor used
let scene = LevelSelectScene(size: self.size) // same size as current scene
// Way 2
// with xCode/SpriteKit visual level editor
// fileNamed is the LevelSelectScene.sks you need to create that goes with your LevelSelectScene class.
guard let scene = LevelSelectScene(fileNamed: "LevelSelectScene") else { return }
let transition = SKTransition.SomeTransitionYouLike
view?.presentScene(scene, withTransition: transition)
}
}
/// Level Select Scene
class LevelSelectScene: SKScene {
....
func loadGameScene() {
// Way 1
// code only, no XCode/SpriteKit visual level editor used
let scene = GameScene(size: self.size) // same size as current scene
// Way 2
// with xCode/SpriteKit visual level editor
// fileNamed is the GameScene.sks you need to create that goes with your GameScene class.
guard let scene = GameScene(fileNamed: "GameScene") else { return }
let transition = SKTransition.SomeTransitionYouLike
view?.presentScene(scene, withTransition: transition)
}
}
/// Game Scene
class GameScene: SKScene {
....
}
I strongly recommend you scratch your storyboard and ViewController approach, and just use different SKScenes and 1 GameViewController.
Hope this helps
Go to the segues and use Show Detail Segues anywhere that you don't want the previous view controller to be kept in the stack. Keep in mind that you will have to reinitialize everything appropriately in those view controllers whenever you do return to them.
If you pay attention, viewDidAppear loads every time that you see the view appear, while with your current setup, viewDidLoad would only be called initially and if you returned to the viewController, only viewDidAppear would be called.
When you use a segue to transition out of a viewController, prepareForSegue is called, but deinit() is only called when you use a show detail segue (or custom segue with those specific properties about it), because the view, like you said, is loaded into memory so it can be retrieved easier.

How can you connect a swift file with an SKscene?

I looked through all posts, WWDC talks and youtube videos, but I still can't figure out how to have multiple SKscenes for different levels and connecting them with swift files in a Game using Spritekit. I want to have a main level board and I managed to open a new scene if you press a SKSpriteNode, but how can I implement game logic to this specific SKScene?
Apologies in advance if it is a silly question, I've been spending ages on it.
You can do it like this:
1) Create .swift file and make a subclass of a SKScene
Go to :
File menu -> New File -> Source -> Swift file
and make subclass of a SKScene
class MenuScene:SKScene {}
2) Create .sks file
Then go to
File menu -> New File -> Resource -> SpriteKit Scene
and make a MenuScene.sks (name it MenuScene without the actual extension).
Repeat this steps for each scene you want to have.
Then to load and start your initial scene. Do this inside your GameViewController.swift:
if let scene = GameScene(fileNamed:"GameScene") {
let skView = self.view as! SKView
//setup your scene here
skView.presentScene(scene)
}
To make a transition to other scene (lets assume that you are in the MenuScene currently) you should do something like this:
if let nextScene = GameScene(fileNamed: "GameScene"){
nextScene.scaleMode = self.scaleMode
let transition = SKTransition.fadeWithDuration(1)
view?.presentScene(nextScene, transition: transition)
}

How to add a sprite from another .swift file?

I have a project I've been working on for some time. I am using Sprite-Kit but now want to be able to add a child node from a swift file that is different from the GameScene.swift file.
Some of main code from the view controller that loads the GameScene is shown here:
let skView:SKView = SKView()
let theScene:SKScene = SKScene()
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let theScene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
theScene.scaleMode = .ResizeFill //.AspectFill
var customSceneSize = CGSizeMake(2560, 1600)
theScene.size = customSceneSize
skView.presentScene(theScene)
makeFakeStuff() // prepares some sample data
}
}
Usually I add sprites in the GameScene.swift file using "self.addChild". That won't work from another .swift file, so I have tried:
theScene.addChild(flyingCell)
and I tried:
skView.scene?.addChild(flyingCell)
These execute without error, but nothing shows on the screen. When I try to otherwise use the identical sprite code and put it in the GameScene.swift file and use "self.addChild" it draws it, so the sprite code (not shown) seems fine (position, zPosition, etc). I also made "flyingCell" a global variable to see if that would help ... nope. Any ideas?
I had 2 things wrong in my code.
The first is visible in my question: I should have declared "theScene" using "var" and not "let"
The second problem was in my gamescene, I needed to put "theScene = self"
Apple DTS helped me solve this problem.

Resources