3
votes

What I want

An infinite background that randomly adds objects (in my cases little stars) to the middle of the screen. Then those objects needs to move out of the screen with a certain speed. This way I want to give the user the feeling they are moving "into space", seeing stars they are passing.

What I have

A single view application with a UIViewController class.

Problem

I think the right way is to add a SKScene which will do the task I want. However, adding the SKScene class next to UIViewController gives me an error: "multiple inheritance from classes 'UIViewController' and 'SKScene'". I need to add the SKScene to an existence UIViewController, in order to call some important functions. When searching for this on Stackoverflow I came across this: SKScene in UIViewController But I can not call certain functions like "override func update(current time: CFTimeInterval){}", because the answer doesn't show how to implement the SKScene class. This answer deletes the whole UIViewController class: Adding an SKScene to a UIViewController?. The other answers are not helping me.

Question

What is the correct way of adding a SKScene class to an existence UIViewController class, so I can accomplish what I want?

Edit: Came across this on 9gag and its exactly what I want: http://9gag.com/gag/aWmZAPZ Those stars are coming from left top, the respawning should be in the middle of the screen at my app.

1
As the answer to the question of your link explains, you cannot directly add an SKScene to a UIView, SKScene isn't a view at all, to display it you must first add it to an SKView. - Pop Flamingo
Ok, but how about adding a SKView to an existing uiviewcontroller? Is that possible? - Petravd1994

1 Answers

0
votes

Certainly, it's possible. Instead of directly add SKScene to UIViewController, you need to warp SKScene by SKView first, and then add SKView to UIViewController

import UIKit
import SpriteKit


class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure the view.
        // Core:- convert the base view/UIView of UIViewController to SKView
        let rootView = self.view as! SKView
        //            skView.showsFPS = true
        //            skView.showsNodeCount = true

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        rootView.ignoresSiblingOrder = true
        rootView.frameInterval = 1

        //init your SKScene
        let rootMenuScene = YourScene(size: rootView.bounds.size)
        rootMenuScene.scaleMode = .resizeFill

        //warp in SKView
        rootView.presentScene(rootMenuScene) 
    }
    ...

}