Add UIView to back of scene in SpriteKit game - ios

I am trying to make a advent calendar with a snow affect in swift2. I am using the game template while using SpiteKit.
Here is my code so far:
GameScene.swift
import SpriteKit
class GameScene: SKScene {
/*override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let location = touch.locationInNode(self)
print(location)
}
}*/
func test()
{
//Generate Doors
//Initilization
var adventDoors = [AdventDoor]()
let offset = CGVector(dx: 10,dy: 10)
var size = CGRectMake(offset.dx, offset.dy, 60, 60)
var ypos:CGFloat = 20
var xpos:CGFloat = 10
var index = 0
var xDoor = AdventDoor(frame: size)
let randomIdentifier = [Int](1...24).shuffle()
for _ in 1...4
{
for i in 1...6
{
size = CGRectMake(xpos, ypos, 60, 60)
xDoor = AdventDoor(frame: size)
xDoor.opaque = false
xDoor.restorationIdentifier = "\(randomIdentifier[index])"
xDoor.generateDoor()
adventDoors.append(xDoor)
print("1...6")
ypos += 80
//xpos += 20
index++
if i == 6
{
print("Moving to next view")
}
}
xpos += 80
ypos = 20
}
size = CGRectMake(10, 500, 300, 60)
xDoor = AdventDoor(frame: size)
xDoor.opaque = false
xDoor.restorationIdentifier = "\(25)"
xDoor.generateDoor()
adventDoors.append(xDoor)
index = 0
for door in adventDoors
{
index++
self.view?.addSubview(door)
}
print("\(index) doors were added")
}
}
GameViewController.swift
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"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 */
scene.scaleMode = .AspectFill
scene.backgroundColor = UIColor.greenColor()
skView.presentScene(scene)
scene.test()
//Snow
let wrappedSnowPath = NSBundle.mainBundle().pathForResource("Snow", ofType: "sks")
if let snowPath = wrappedSnowPath
{
let snowEmitter:SKEmitterNode = NSKeyedUnarchiver.unarchiveObjectWithFile(snowPath) as! SKEmitterNode
let screenBounds = UIScreen.mainScreen().bounds
snowEmitter.position = CGPointMake(screenBounds.width, screenBounds.height)
scene.addChild(snowEmitter)
}
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
AdventDoor.swift just contains a custom UIView (AdventDoor) along with some more functions
This is what it looks like.
As you can see, the snow SKEmitterNode particles are behind the AdventDoors and not in front.
How would I get my snow to display in front of the UIView Advent Doors instead of behind?

Instead of addsubview for the door, What you need to do is rearrange how your views are laid out. What you need is a UIView as your main view, then you add the SKView as a child to the main view. Then if you want to add the doors in during the scene creation process, you need to do self.view.superview.insertSubView(door, atIndex:0) or self.view.superview.insertSubView(door, belowSubView:self.view) so that the doors are placed behind the scene subview

Related

Segue between SKScene and UIViewController

I'm writing simple math game with swift 3 and I have a problem with segues. I have two GameViewController's, oneUIViewController and one NavigationViewController.
I want to make two menus, one with game modes and one with difficulties, I want that the difficulties menu be interactive and have gravity so I decided to make it in SkScene. Everything works fine except segue between SkScene with dark screen and difficulties menu when user lost the game. I write a protocol which works when I'm going from main menu to second menu but when I'm going from SkScene with game it doesn't. I was trying to make a manual segue but protocol doesn't want to execute.
MyGVViewController code:
import UIKit
import SpriteKit
import GameplayKit
enum skad1 {
case game,menu
}
var skad = skad1.gra
class MyGVViewController: UIViewController, GameViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "Menugame") {
let gameScene = scene as! MySKScene
gameScene.gameViewControllerDelegate = self
gameScene.scaleMode = .aspectFill
gameScene.size = view.bounds.size
// Present the scene
view.presentScene(gameScene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
func goback() {
print("goback executed")
let view = self.view as! SKView?
view?.presentScene(nil)
navigationController?.popViewController(animated: true)
}
func goback2() {
print("goback2 executed")
let view = self.view as! SKView?
view?.presentScene(nil)
self.performSegue(withIdentifier: "comeback", sender: nil)
}
}
My SkScene with difficulties menu code:
import GameKit
import SpriteKit
import CoreMotion
protocol GameViewControllerDelegate: class {
func goback()
func goback2()
}
class MySKScene: SKScene {
//Variables
var motionManager: CMMotionManager!
var ball = SKSpriteNode()
var ball1 = SKSpriteNode()
var ball2 = SKSpriteNode()
var ball3 = SKSpriteNode()
var ball4 = SKSpriteNode()
weak var gameViewControllerDelegate: GameViewControllerDelegate?
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if ball.contains(location){
showgame(zakres: 200)
}else if ball1.contains(location){
showgame(zakres: 100)
}else if ball2.contains(location) {
showgame(zakres: 50)
}else if ball3.contains(location) {
showgame(zakres: 150)
}else if ball4.contains(location) {
if skad == .menu{
print("should execut goback")
self.gameViewControllerDelegate?.goback()
}else{
print("should execut goback2")
self.gameViewControllerDelegate?.goback2()
}
}
}
}
func showgame(zakres:Int) {
if let view = self.view {
range = zakres
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
let gameScene = scene as! GameScene
gameScene.scaleMode = .aspectFill
// Present the scene
gameScene.size = view.bounds.size
view.presentScene(gameScene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override func didMove(to view: SKView) {
ball = self.childNode(withName: "ball") as! SKSpriteNode
ball1 = self.childNode(withName: "ball1") as! SKSpriteNode
ball2 = self.childNode(withName: "ball2") as! SKSpriteNode
ball3 = self.childNode(withName: "ball3") as! SKSpriteNode
ball4 = self.childNode(withName: "ball4") as! SKSpriteNode
motionManager = CMMotionManager()
motionManager.startAccelerometerUpdates()
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
border.friction = 0
border.restitution = 0
self.physicsBody = border
}
override func update(_ currentTime: TimeInterval) {
if let accelerometerData = motionManager.accelerometerData {
physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.x * 20, dy: accelerometerData.acceleration.y * 35)
}
}
}
PS.
I'm reading what I wrote and I have to correct it, in difficulties menu I have a button which execute protocol that hide SKScene and show main menu. It works only when I'm going from main menu but when segue is from game when user lost, protocol isn't executed

iCarousel in Sprite Kit

Explanation
I'm trying to build a character selection menu similar to Crossy Road's one (as you can see here). So I found this iCarousel, which would help me with all of it, but everything I read talk about implementing it to a ViewController, which isn't my case. I'm using GameScene and I didn't found anything talking about it. Is there anyway I could implement it to my game? or even another effect similar to the character selection menu I mentioned above?
Attempt (beyowulf)
You can download it here.
GameScene.swift
import SpriteKit
class GameScene: SKScene {
var show = SKSpriteNode()
var hide = SKSpriteNode()
func showCharPicker(){
NSNotificationCenter.defaultCenter().postNotificationName("showCharPicker", object: nil)
}
func hideCharPicker(){
NSNotificationCenter.defaultCenter().postNotificationName("hideCharPicker", object: nil)
}
override func didMoveToView(view: SKView) {
/* Setup your scene here */
print("didMoveToView")
show = SKSpriteNode(imageNamed: "show")
show.anchorPoint = CGPointZero
show.position = CGPointZero
addChild(show)
hide = SKSpriteNode(imageNamed: "hide")
hide.anchorPoint = CGPointZero
hide.position = CGPoint(x: self.frame.width / 2 - hide.frame.width / 2, y: 0)
addChild(hide)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches{
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
if node == show{
print("show")
showCharPicker()
}
else if node == hide{
print("hide")
hideCharPicker()
}
}
}
}
GameViewController.swift
import UIKit
import SpriteKit
class GameViewController: UIViewController, iCarouselDataSource, iCarouselDelegate{
var squaresArray : NSMutableArray = NSMutableArray()
#IBOutlet weak var carousel: iCarousel!
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func showCarousel(){
self.carousel.hidden = false
}
func hideCarousel(){
self.carousel.hidden = true
}
override func viewDidLoad(){
super.viewDidLoad()
// Configure iCarousel
carousel.dataSource = self
carousel.delegate = self
carousel.type = .CoverFlow
carousel.reloadData()
self.carousel.hidden = true
// Register showCarousel and hideCarousel functions
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showCarousel), name: "showCharPicker", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.hideCarousel), name: "hideCharPicker", object: nil)
// Configure view
let skView = SKView()
self.view.insertSubview(skView, belowSubview: self.carousel)
skView.frame = self.view.bounds
// Additionals
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
// Configure scene
let scene = GameScene(size:self.view.bounds.size)
scene.scaleMode = .ResizeFill
scene.size = self.view.bounds.size
skView.presentScene(scene)
}
//iCarousel
override func awakeFromNib(){
super.awakeFromNib()
squaresArray = NSMutableArray(array: ["square1","square2","square3"])
}
func numberOfItemsInCarousel(carousel: iCarousel) -> Int{
return squaresArray.count
}
func carousel(carousel:iCarousel, didSelectItemAtIndex index:NSInteger){
//self.hideCarousel()
}
func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView{
var itemView: UIImageView
if (view == nil){
itemView = UIImageView(frame:CGRect(x:0, y:0, width:200, height:200))
itemView.contentMode = .Center
}
else{
itemView = view as! UIImageView;
}
itemView.image = UIImage(named: "\(squaresArray.objectAtIndex(index))")
return itemView
}
func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat{
if (option == .Spacing){
return value * 2
}
return value
}
}
What's happening:
Thanks in advance,
Luiz.
You can use NSNotifications to show your character picker. You just need to observe the notifications posted by your SKScene. Your viewDidLoad should look something like:
override func viewDidLoad(){
super.viewDidLoad()
carousel.type = .CoverFlow
carousel.reloadData()
let spriteKitView = SKView()
spriteKitView.frame = self.view.bounds
self.view.insertSubview(spriteKitView, belowSubview: self.carousel)
spriteKitView.showsFPS = true
spriteKitView.showsNodeCount = true
spriteKitView.ignoresSiblingOrder = true
self.gameScene = GameScene(size:self.view.bounds.size)
self.gameScene.scaleMode = .AspectFill
self.gameScene.imageName = self.images[0] as! String
self.carousel.hidden = true
spriteKitView.presentScene(self.gameScene)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showCarousel), name: gameScene.kShowNotification, object: nil)
}
You'll want to implementing carousel(carousel:iCarousel, didSelectItemAtIndex index:NSInteger) so you know what is selected, and so you can return to game play. For example:
func carousel(carousel:iCarousel, didSelectItemAtIndex index:NSInteger)
{
self.gameScene.imageName = self.images[index] as! String
self.hideCarousel()
}
You also need to remove observing before your view controller is deallocated.
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
Your SKScene can then post a notifications:
import SpriteKit
class GameScene: SKScene {
var imageName = "square1"{
didSet{
self.hidden = false
self.childNode.texture = SKTexture(imageNamed: imageName)
}
}
let kShowNotification = "showPicker"
var childNode = SKSpriteNode()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.childNode = SKSpriteNode(imageNamed: imageName)
self.childNode.anchorPoint = CGPointZero
self.childNode.position = CGPointZero
self.addChild(self.childNode)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.showCharPicker()
}
func showCharPicker()
{
self.hidden = true
NSNotificationCenter.defaultCenter().postNotificationName(kShowNotification, object: nil)
}
}
If you want to change hit detection, you need to subclass the view for which you need it to change. This case your iCarousel view.
You can then either override hitTest or pointInside. I've created an iCarousel subclass and overrode pointInside to only return true when the point is inside one of the carousel's contentView's subviews.
class CarouselSubclass: iCarousel {
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
var inside = false
for view in self.contentView.subviews
{
inside = CGRectContainsPoint(view.frame, point)
if inside
{
return inside
}
}
return inside
}
}
You need to remember to change the class of your carousel in interface builder and update your outlet as well.

SKSpriteNode hidden under a UI Background Image

I have an SKSpriteNode that functions properly. But when I add a UIImage, the SKSpriteNode becomes hidden behind the UIImage. I have been trying to figure out why, but I am having a little bit of trouble and can't seem to figure out what I am missing to allow the SKSSpriteNode to appear on top of the UI background Image, instead of behind it where it can't be seen. Any help would be greatly appreciated!
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"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 */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
import SpriteKit
import SceneKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var blueBall:SKSpriteNode!
override func didMoveToView(view: SKView) {
self.physicsWorld.gravity = CGVectorMake(0.0, -5.0)
self.physicsWorld.contactDelegate = self
blueBall = SKSpriteNode( imageNamed: "ball")
blueBall.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
blueBall.physicsBody = SKPhysicsBody(circleOfRadius: blueBall.size.width / 1.5 )
blueBall.physicsBody!.dynamic = true
blueBall.physicsBody!.allowsRotation = false
self.addChild(blueBall)
}
override func touchesBegan(touches: Set<UITouch> , withEvent event: UIEvent?) {
self.blueBall.physicsBody?.velocity = CGVectorMake(35, 0)
self.blueBall.physicsBody?.applyImpulse(CGVectorMake(4, 10))
}
}
For draw order use the zPosition property:
In your case you will need to give the Sprite you want to be displayed in front a higher .zPosition value than the one to be displayed further back.
Example: ball.zPosition = 10
zPosition definition:
The height of the node relative to its parent.
Tipps:
The default value is 0.0. The positive z axis is projected toward the viewer so that nodes with larger z values are closer to the viewer.

SpriteKit, Swift 2.0 - ScrollView Missing from Scene Startup via Button

I recently implemented a scrollView into my GameViewController and it works really well, but the tutorial I looked at had only one scene which was the start up scene (GameScene) rather than a seperate scene which I'm going to be calling "Menu" so I managed to get it to launch the Menu scene rather than the regular "GameScene" but when I go from GameScene to the Menu scene with a button that I implemented in GameScene, the scrollview does not work, but it does show the pictures, but I just can't scroll through them.
My question is how do I get scrollView to work when I use the button (that is in GameScene) to go to the Menu scene?
This is the button (which is In GameScene)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch: UITouch = touches.first!
let location: CGPoint = touch.locationInNode(self)
let node: SKNode = self.nodeAtPoint(location)
if (node == menubutton) {
let MenuScene = Menu(size: self.size, viewController: viewController)
let transition = SKTransition.flipVerticalWithDuration(0.5)
MenuScene.scaleMode = SKSceneScaleMode.AspectFill
self.scene!.view?.presentScene(MenuScene, transition: transition)
}
Here is my Menu scene:
import Foundation
import SpriteKit
let kMargin: CGFloat = 40
var backButton = SKSpriteNode()
var selectButton = SKSpriteNode()
class Menu: SKScene {
let world2 = SKSpriteNode()
private var imageSize = CGSize.zero
private weak var viewController: GameViewController?
init(size: CGSize, viewController: GameViewController?) {
self.viewController = viewController
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
assert(false, "Use init(size:viewController:)")
super.init(coder: aDecoder)
}
override func didMoveToView(view: SKView) {
physicsWorld.gravity = CGVector.zero
imageSize = SKSpriteNode(imageNamed: "card_level01").size
let initialMargin = size.width/2
let marginPerImage = kMargin + imageSize.width
world2.size = CGSize(width: initialMargin*2 + (marginPerImage * 7), height: size.height)
addChild(world2)
for i in 1...8 {
let sprite = SKSpriteNode(imageNamed: String(format: "card_level%02d", i))
sprite.position = CGPoint(x: initialMargin + (marginPerImage * (CGFloat(i) - 1)), y: size.height / 2)
world2.addChild(sprite)
}
}
override func update(currentTime: NSTimeInterval) {
viewController?.applyScrollViewToSpriteKitMapping()
}
Here is my GameViewController
import UIKit
import SpriteKit
class GameViewController: UIViewController {
var scrollView: UIScrollView!
var contentView: UIView!
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let skView = view as! SKView
if (skView.scene === Menu.self) {
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
let scene = Menu(size: skView.bounds.size, viewController: self)
scene.scaleMode = .AspectFill
skView.presentScene(scene)
scrollView = UIScrollView(frame: self.view.bounds)
scrollView.delegate = self
scrollView.contentSize = scene.world2.frame.size
view.addSubview(scrollView)
contentView = UIView(frame: CGRect(origin: CGPoint.zero, size: scene.world2.size))
contentView.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.2)
scrollView.addSubview(contentView)
applyScrollViewToSpriteKitMapping()
}
}
func applyScrollViewToSpriteKitMapping() {
let origin = contentView.frame.origin
let skPosition = CGPoint(x: -scrollView.contentOffset.x + origin.x, y: -scrollView.contentSize.height + CGRectGetHeight(view.bounds) + scrollView.contentOffset.y - origin.y)
let skView = view as! SKView
if let scene = skView.scene as? Menu {
scene.world2.position = skPosition
}
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.Portrait
} else {
return UIInterfaceOrientationMask.All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func shouldAutorotate() -> Bool {
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
extension GameViewController: UIScrollViewDelegate {
}
I recently helped another member with a similar question, check it out it might be helpful to you
How to create a vertical scrolling menu in spritekit?
In my way I am subclassing scroll view and therefore can add it to SKScenes directly rather than the view controllers.
If you want the scrollView on more than 1 SKScene without duplicate code than need to subclass your SKScnenes
class BaseScene: SKScene ...
// Add scroll view
class Menu: BaseScene...
class GameScene: BaseScene ...
As a side note, you shouldn't really reference your viewController in your SKScenes, they shouldn't have to know about each other.

Halt when presenting ViewController with SKScene

EDIT: OK, so this happens even with an empty SpriteKit scene!
What could be wrong here??
Why does iOS need 2 seconds to display SpriteKit scene??
EDIT 2: First time i click on tab bar to display view controller with SKScene it displays immediately, but every next time i try to navigate back to this view controller it will take it 2 seconds to display!
I have a a tab bar controller in my app with multiple different viewControllers.
One of them contains a SpriteKit scene, with a couple of nodes, 5 of them, nothing too heavy.
In simulator everything is fine, but when testing on the device i noticed that sometime there is a big halt ( around 2 seconds! ) when changing to ViewController with the SpriteKit scene.
Other times there is no halt and view is displayed immediately.
Now, i know there must be something I'm doing wrong here, because iOS should definitely be able to handle this.
This is my viewDidLoad function inside the viewController with the spriteKit scene:
override func viewDidLoad() {
super.viewDidLoad()
if let scene = MyScene(fileNamed:"MyScene") {
// Configure the view.
scene.switchView = switchView
let parentNode = scene.childNodeWithName("WholeObject") as! SKSpriteNode
let contentNode = scene.childNodeWithName("CenterNode") as! SKSpriteNode
addPhotoToFrame(contentNode, photoName: "woman", maskName: "circleMask")
let node1 = parentNode.childNodeWithName("node1") as! SKSpriteNode
addPhotoToFrame(zealNode1, photoName: "motherCircleImage", maskName: "circleMaskSmall")
let node2 = parentNode.childNodeWithName("node2") as! SKSpriteNode
addPhotoToFrame(zealNode2, photoName: "hairstylistCircleImage", maskName: "circleMaskSmall")
let node3 = parentNode.childNodeWithName("node3") as! SKSpriteNode
addPhotoToFrame(zealNode3, photoName: "dietCircleImage", maskName: "circleMaskSmall")
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 */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
hi deloki i created a new project in swift and come with a solution its working fine on device..... check out my code
here is my GameViewController which call GameScene
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile1(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
var skView:SKView!
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile1("GameScene") as? GameScene {
// Configure the view.
let graphRect:CGRect = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
skView = SKView();
skView.frame=graphRect
skView.showsFPS = true
skView.showsNodeCount = true
self.view.addSubview(skView)
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
let s2=GameViewController1();
self.presentViewController(s2, animated: true, completion: { () -> Void in
//
})
}
}
}
override func viewDidDisappear(animated: Bool) {
if((skView) != nil)
{
skView .removeFromSuperview();
skView=nil;
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
here is my GameViewController1 which call MyScene1
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController1: UIViewController {
var skView:SKView!
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("MyScene1") as? GameScene {
// Configure the view.
let graphRect:CGRect = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
skView=SKView()
skView.frame=graphRect
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 */
// scene.scaleMode = .AspectFill
self.view.addSubview(skView)
skView.presentScene(scene)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
let s2=GameViewController();
self.presentViewController(s2, animated: true, completion: { () -> Void in
//
})
}
}
}
override func viewDidDisappear(animated: Bool) {
if((skView) != nil)
{
skView .removeFromSuperview();
skView=nil;
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
creating SKview from storyboard i just created it from programmitically and every 2 second i am switching from one view to another and its working fine on all device but one thing i used Xcode 6.4 and ios9
you can download link from http://www.filedropper.com/tryit
I have no idea what triggers the issue but pausing before the view disappeared fixed it for me.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.contentView.paused = false
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.contentView.paused = true
}

Resources