There seems to be so many contradicting ideas on this topic.
I simply wish to have my menu in a UIViewController and my game in the SKScene
In my SKScene I used:
self.removeFromParent()
self.view?.presentScene(nil)
The nodes are removed but the scene is still in place as I still have the grey background and fps counter. Can I return to the View aspect of the UIViewController and hide the scene?
My method one implementation:
RootViewController:
class RootViewController: UIViewController {
var menu = MenuViewController()
var game = GameViewController()
override func viewDidLoad() {
super.viewDidLoad()
print("root")
MenuPresent()
}
func GamePresent() {
self.addChildViewController(game)
self.view.addSubview((game.view)!)
game.didMoveToParentViewController(self)
}
func MenuPresent() {
self.addChildViewController(menu)
self.view.addSubview((menu.view)!)
menu.didMoveToParentViewController(self)
}
func menuDismiss() {
menu.willMoveToParentViewController(nil)
menu.removeFromParentViewController()
menu.view.removeFromSuperview()
}
}
MenuViewController:
class MenuViewController: UIViewController {
//var root = RootViewController()
override func viewDidLoad() {
super.viewDidLoad()
print("menu")
}
}
The print("menu") appears in my console, But the actual view and all assets of the MenuViewController do no appear.
On the other hand my GameViewController and it's SKScene work fine.
Views and scenes are two different things. Scenes are held inside of a view. You would have to simply present a scene within your menu view or transition to another view and present an SKScene from there. The code to present the scene might look like this:
let scene = GameScene(fileNamed: "GameScene")
let skView = self.view as! SKView
scene?.scaleMode = .AspectFit
skView.presentScene(scene)
First you need to know that SKScene and UIViewController are totally two different things. The hierarchy is typically as following:
UIViewController --> UIView(SKView) --> SKScene
So you SKScene is presented in a SKView which can be a UIView, then the UIView is presented in a UIViewController.
Once you know the hierarchy, everything is easy. There are many ways to use different UIViewController for menu and GameScene stuff.
Method One
For example, you can have a RootViewController, a GameViewController and a MenuViewController. The RootViewController is the initial ViewController when the app launches.
In the RootViewController, you can create a function to present the GameViewController:
func setupGameViewController() {
self.gameViewController = GameViewController()
self.addChildViewController(gameViewController!)
self.view.addSubview((gameViewController!.view)!)
gameViewController?.didMoveToParentViewController(self)
}
You need to present you SKScene in GameViewController, I guess you should be familiar with this step.
Then when you need to display the menu, you can add the MenuViewController to RootViewController with a function like:
func setupMenuViewController() {
self.menuViewController = MenuViewController()
self.addChildViewController(menuViewController!)
self.view.addSubview((menuViewController!.view)!)
menuViewController?.didMoveToParentViewController(self)
}
You also need to present you menuView in this ViewController, which I suppose you already know.
Also create a function to dismiss the MenuViewController:
func removeMenuViewController(){
self.menuViewController?.willMoveToParentViewController(nil)
self.menuViewController?.removeFromParentViewController()
self.menuViewController?.view.removeFromSuperview()
}
And everything is done.
Method Two
You can also have only one UIViewController, but create you menu as a UIView, then you can use self.view.addSuview(menuView) to present your menu. Of course you root view, which is the self.view as SKView is still there, but it doesn't matter because it's hidden behind the menuView.
A Note for your updated question
You cannot remove the scene because the scene is actually self.view as SKView, self.view is the root view of a UIViewController, it cannot be removed. If you really want to remove you scene (for most cases, it's not necessary), you can create a new SKView that present your SKScene, then add this SKView to your UIViewController by self.view.addSubview(skView), when you want to completely remove the scene, just use skView.removeFromSuperview().
Related
When testing my app I realised that going to the view controller which presents my scene and back again increases the used space in memory. So I run instruments to learn what wasn’t deallocated. I found that there was some instances of my scene taking up space. How can I fix it?
I have a property in my scene class to access its view controller (which I defined as weak to avoid a retain cycle)
The concerning lines in my scene class are:
weak var viewController: MyViewControllerClass?
func exitFunction () {
viewController.dismiss(animated: true , completion: nil)
self.view!.presentScene(nil)
}
All your scenes should belong to the same view controller, that is to say in a sprite kit game there is only one view controller.
You should define your scenes and the SKView to present them on in this view controller like so:
class GameViewController: UIViewController {
var skView: SKView?
var mainMenu: MainMenu?
override func viewDidLoad() {
super.viewDidLoad()
skView = self.view as! SKView?
}
Inside your scene make sure you are deallocating your resources properly:
override func willMove(from view: SKView) {
removeAllChildren()
}
deinit {
//Deallocate your resources here
}
WillMove is called each time you move from the scene to another.
Finally when you show your scenes from inside your viewController class make sure you deallocate old ones first:
func showMainMenu(_ notification: Notification) {
deallocScenes()
mainMenu = MainMenu(fileNamed: "MainMenu")
mainMenu?.scaleMode = .fill
skView!.presentScene(mainMenu)
}
func deallocScenes(){
mainMenu = nil
levelSelection = nil
credits = nil
}
I am making this app with multiple features, one of which is supposed to be a game. the normal collision game where you hit objects and score. but my app is a Single based application.
when i create a new swift file, how can i add a SKScene to a UIViewController?
any help will be appreciated.
SKScene needs to be added to an SKView which is a subclass of UIView. When you create the view controller, you can either set the view property to be an SKView or add an SKView as a subview, then add your SKScene to that SKView via the presentScene: method on SKView. Here's an example on how you could achieve that:
import SpriteKit
class SomeViewController: UIViewController {
func viewDidLoad() {
super.viewDidLoad()
let sceneView = SKView(frame: view.frame)
let scene = SKScene()
// Do any other scene setup here
view.addSubview(sceneView)
sceneView.presentScene(scene)
}
}
Sorry if there are small syntactical errors. Didn't have a chance to test this and my memory of the SpriteKit API is hazy. Hope this helps!
QUESTION: How can I dismiss a ViewController from my GameScene.swift ?
SITUTATION: I have 2 VCs in my SpriteKit Game, like so:
ViewController.swift ----Press Play-----> GameViewController
When the player loses, I want to dismiss the GameViewController so the player can press play again. I check for the player's loss in my GameScene.swift and would like to dismiss the GameVC from there.
N.B.: Googled this without success.
WHAT I TRIED:
1) Creating a gameVC instance in my GameScene.swift and dismissing it like so:
let gameVC = GameViewController()
gameVC.dismissViewController(false,completion: nil)
2) Doing:
self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
Those don't work for obvious reasons ^^
You don't want to "grab" the existing instance: https://pragprog.com/articles/tell-dont-ask
You need to either hand GameScene a reference to the view controller so it can dismiss it, or use the delegate pattern to communicate backwards to a controlling object that the VC should be dismissed/dismiss itself.
A simple example… you can add a GameViewController property to GameScene, then dismiss the VC at the appropriate time:
class GameScene: SKScene {
var gameVC: GameViewController?
func gameDidEnd() {
gameVC?.dismissViewControllerAnimated(true) {
// if desired, do any cleanup after the VC is dismissed
}
}
}
Then, just set this property when creating the GameScene object in the first place:
if let gameScene = GameScene(fileNamed: "MyScene") {
gameScene.gameVC = someGameVC
}
This simple approach will tightly couple GameScene and GameViewController, making it a bit more difficult if you ever want to use one of these objects without the other. But for this simple use case, it may be fine.
I've follow some of your discussion. I want to add some code, because usually I prefeer to work with one ViewController or two and many SKScene and SKNode, but in this case could be useful to have a currentViewController reference:
class MyModelScene: SKScene {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var currentViewController : MyModelViewController! = MyModelViewController()
// MyModelViewController is a customized UIViewController
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
print("---")
print("∙ \(NSStringFromClass(self.dynamicType))")
print("---")
}
}
class Level1Scene: MyModelScene {
...
}
In the UIViewController:
class PreloadViewController: MyModelViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = Level1Scene(fileNamed:"Level1Scene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsPhysics = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .ResizeFill
scene.currentViewController = self
skView.presentScene(scene)
}
}
}
With this code , you've always a currentViewController reference in your SKScene and you can check if it's the correct viewController you want to dismiss or not.
Hi I have a segues from the main menu UIViewController to start playing the game I created. But if i want to exit back to main menu there is no prepareForSegue function in SpriteKit.
How can I unwind back to the main menu from my scene?
I am using touches began to handle events instead of UIButtons
You have call performSegue from the ViewController containing the SKView not the SKScene. Create a weak variable inside SKScene pointing to the GameViewController. Set it when the SKScene is created. Then call performSegue on this property.
//Game Scene
class GameScene {
weak var gameViewController : GameViewController?
}
// GameViewController
override func viewDidLoad() {
//Other code
scene.gameViewController = self
skView.presentScene(scene)
}
When you want to perform the segue inside GameScene, call
// Inside GameScene
self.gameViewController?.performSegueWithIdentifier("indentifer", sender: self)
To go back the the main view.
self.gameViewController?.navigationController?.popViewControllerAnimated(true)
Inside my main UIViewController, I'm defining two SKScenes. I want to present only gameScene at first, and then present uiScene later, triggered by an action in gameScene (hitting the pause button).
The problem is that skView, the view containing both scenes, is not recognized outside of the UIViewController.
The code is below. Any help would be appreciated.
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let skView = view as SKView
let gameScene = GameScene(size: view.bounds.size)
gameScene.scaleMode = .ResizeFill
skView.presentScene(gameScene)
let uiScene = UIScene(size: view.bounds.size)
uiScene.scaleMode = .ResizeFill
uiScene.backgroundColor = UIColor.clearColor()
//skView.presentScene(uiScene) // I want to present this line from within gameScene.
}
}
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = uiScene(size: size)
self.view?.presentScene(scene, transition:reveal)
You can transition from one scene to another from within the scene. My code is pulled from http://www.raywenderlich.com/84434/sprite-kit-swift-tutorial-beginners in the last section.
Remember to import the header of the scene you are transitioning TO in the scene you are transitioning FROM.