How can I get the safeAreaLayout info for my GameScene? - swift

Am trying to develop a game and am not using storyboard at all. Am building it all via code.
I know how to get the safeAreaLayout info, thanks to this forum) for a UIViewController. My thought was I'd be able to attach my GameScene: SKScene to that and go from there. Found out the hard way that's not the case. I have searched so hard and have tried all the example I found find for the likes of
override func viewDidLayoutSubviews()
and
func viewDidAppear(_ animated: Bool)
And every method I've tried returns either sets of 0's, or the full height of the screen 812
I would like to think that there is a proper method for getting the proper safeArea info to the initial GameScene of my app. Is there?

Hei,
You get the 812 pixels height because that's the scene height. In SpriteKit the games are full screen, you don't need to worry about the safe areas.
From GameViewController present the scene you want to display, in my case MainScene.
if let view = self.view as! SKView?
{
// create a new scene of type Main Scene
let scene = MainScene()
// set the new (MainScene) settings
scene.scaleMode = .resizeFill
scene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
// present the scene
view.presentScene(scene)
}
If you want to know the size of the scene in MainScene, just get the values like this.
class MainScene: SKScene
{
override func didMove(to view: SKView)
{
let screenHeight = self.scene!.size.height
let screenWidth = self.scene!.size.width
}
}

Related

Background is not filling the whole view SpriteKit

For some reason my code will not fill the whole SKScene. Here is the code that I am using on Xcode 12 Beta 5.
GameScene.swift
class GameScene: SKScene {
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "space")
background.zPosition = 0
background.anchorPoint = CGPoint(x: 0.5, y: 0.5) // default
background.position = CGPoint(x: frame.midX, y: frame.midY)
print("frame.size \(frame.size)")
print("self.size \(self.size)")
print("view \(view.frame.size)")
background.size = CGSize(width: self.size.width, height: self.size.height)
self.addChild(background)
}
}
GameViewController.swift
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GKScene(fileNamed: "GameScene") {
if let sceneNode = scene.rootNode as! GameScene? {
// Present the scene
if let view = self.view as! SKView? {
sceneNode.size = view.bounds.size
sceneNode.anchorPoint = CGPoint.zero
sceneNode.scaleMode = .aspectFit
print("view.bounds.size \(view.bounds.size)")
view.presentScene(sceneNode)
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 var prefersStatusBarHidden: Bool {
return true
}
}
Also for some reason, my view size is reporting ->
frame.size (320.0, 480.0) self.size (320.0, 480.0) view (320.0,
480.0)
But my GameScene.sks is set to -> w750, h1336
Why is my code cutting off the tops and the bottoms of the background?
This is going to sound dumb, but do you have a launch Screen? I was having the same problem which would only happen in Xcode 12 and not 11, but the main difference I found was Xcode 11 has a launch screen. Once I added the launch screen storyboard and added it to my plist my SCNView would fill the screen. I am not sure why this would cause the view not to follow the constraints, but after adding it to my other projects it fixes the issue.
Edit:
You do not need to have a launch screen storyboard, you can just add your main storyboard that displays you scene in the plist under "Launch screen interface file base name".
This is definitely caused by not having a launch screen assigned. It's very odd that Xcode 12 has this behavior for SpriteKit by default. I'm sure many many people will be stumped and confused. I noticed that the main visible difference to earlier versions was the lack of a launch screen.
You can either create a launch screen and assign it or define Main.storyboard as the launch screen, as proposed earlier. Probably the easiest thing to just get it working is to go to the project target, then General and choose "Main" where it says "Launch Screen File". This will make it work as expected.
Update: This is still happening in Xcode 12.4 (12D4e). Surprisingly, the launch screen will be missing in a brand-new iOS-only project, whereas it's there in a multi-platform project. It seems like this is an oversight on Apple's part.
How to select Main as your project's Launch Screen File:

Assigning SCNScene to SCNView - found nil while unwrapping Optional value

Recently, I decided to apply my previous knowledge in C++ and Python to learning Swift. After which, I decided to see what I could do with the SceneKit framework. After hours of checking through the documentation, and consulting a tutorial, I have to wonder what's going wrong with my code:
class GameViewController: UIViewController {
var gameView:SCNView!
var gameScene:SCNScene!
var cameraNode:SCNNode!
override func viewDidLoad() {
super.viewDidLoad()
initScene()
initView()
initCamera()
}
func initView() {
//initialize the game view - this view holds everything else in the game!
gameView = self.view as! SCNView
//allow the camera to move to gestures - mainly for testing purposes
gameView.allowsCameraControl = true
//use default lighting while still practicing
gameView.autoenablesDefaultLighting = true
}
func initScene() {
//initialize the scene
gameScene = SCNScene()
//set the scen in the gameView object to the scene created by this function
gameView.scene = gameScene
}
func initCamera() {
//create a node that will become the camera
cameraNode = SCNNode()
//since a node can be any object in the scene, this needs to be set up as a camera
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3 (x:0, y:5, z:15)
}
}
After more checking through the documentation and making sure that I was now copying from the tutorial directly to get it to work, I still have no luck with this. According to a lot of the other questions I found here on StackOverflow, it looks like it has something to do with the forced unwrapping, the exclamation points, but I'm not exactly sure why that is.
I've probably been staring the answer in the face combing through this documentation, but I'm not quite seeing what the problem is.
Also, apologies if my comments are a bit long and/or distracting.
You have the following problems:
1) you should re-order the initializations in your viewDidLoad, doing so:
initView() // must be initialized before the scene
initScene() // you have been crashing here on getting `gameView.scene`, but gameView was nil
initCamera()
2) cameraNode is not attached on the rootNode, so you may add the following code at the end of initCamera:
gameScene.rootNode.addChildNode(cameraNode)

Swift 3 (SpriteKit): Reseting the GameScene after the game ends

I am wanting to 'reset' and 'restart' the GameScene so it is as if the GameScene was first called. I have looked at different methods for doing this, but each time I get a warning that I'm trying to add a node to a parent which already has a parent. However, in my code I delete all my existing nodes so I'm really confused as to how to reset the GameScene. This is how I do it now (this code is called when I want to restart the GameScene from scratch and it is called within the GameScene class):
let scene = GameScene(size: self.size)
scene.scaleMode = .aspectFill
let animation = SKTransition.fade(withDuration: 1.0)
self.view?.presentScene(scene, transition: animation)
self.removeAllChildren()
self.removeAllActions()
self.scene?.removeFromParent()
1.Edited: I realised that why I was getting this warning: "I'm trying to add a node to a parent which already has a parent" was because I had all the variables for the scene outside of the class and as global variables. However, now when the game restarts, the game is in the bottom left corner. Why is this the case and how do I fix this? - FIXED
2.Edited: Everything works fine now, but now my concern is that deinit{} isn't called even though every node is deleted and the fps doesn't drop over time. Here is what I have in my GameViewController for setting the scene and in my GameScene (every instance relating to the scenes so basically all that is relevant):
import UIKit
import SpriteKit
import GameplayKit
var screenSize = CGSize()
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
screenSize = scene.size
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
Then my GameScene is basically:
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
//Declare and initialise variables and enumerations here
deinit{print("GameScene deinited")}
override func didMove(to view: SKView) {
//Setup scene and nodes
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//Do other things depending on when and where you touch
//When I want to reset the GameScene
let newScene = GameScene(size: self.size)
newScene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
newScene.scaleMode = self.scaleMode
let animation = SKTransition.fade(withDuration: 1.0)
self.view?.presentScene(newScene, transition: animation)
}
Any answers would be greatly appreciated :)
How to reset the scene?
You just have to present a new, same scene again whenever you want. So, you are doing it fine.
Possible leaking problems?
Also, if you don't have leaks in your game, means no strong reference cycles, you don't even need self.removeAllChildren() and self.removeAllActions()... Of course if you explicitly want to stop actions before transition animation starts, the using this method make sense. The point is, when scene deallocates, all objects that depends on it should / will deallocate as well.
Still, if you don't know from the beginning what you are doing and how to prevent from leaks, eg. you are using strong self in block which is a part of an action sequence, which repeats forever, then you certainly have a leak, and self.removeAllActions() might help (in many cases, but it is not an ultimate solution). I would recommend to read about capture lists and ARC in general because it can be useful to know how all that work just because of these situations.
Scene is a root node
Calling removeFromParent() on a scene itself has no effect. Scene is a root node, so it can't be removed in your current context. If you check scene's parent property you will notice that it is nil. Of course it is possible to add a scene to another scene, but in that case, the scene which is added as a child, will act as an ordinary node.
And finally, how to present the new scene ? Easy, like this:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let newScene = GameScene(size: self.size)
newScene.scaleMode = self.scaleMode
let animation = SKTransition.fade(withDuration: 1.0)
self.view?.presentScene(newScene, transition: animation)
}
If something doesn't work for you, it is likely that you have leaks (means your scene isn't deallocated). To check this, somewhere in your GameScene override deinit method, like this:
deinit{print("GameScene deinited")}
To explain you this a bit further... What should happen is that you should present a new scene, a transition should occur, an old scene should be deallocated, and you should see a new scene with an initial state.
Also overriding deinit will just tell you if the scene is deallocated properly or not. But it will not tell you why. It is up to you to find what in your code retaining the scene.
There are 2 main ways that I can think of that do this. The main way that I go this is that if the game is over, (due to the character health falling to zero, or they collide with an object that causes the round to be over, or time is up or whatever), when that happens I like to transition to a new scene that is a summary screen of their score, how far they made it etc.
I do this by having a bool variable in the main GamePlay scene like this.
var gameOver: Bool = false
Then in the code that fires off to cause the game to end set that variable = true.
In the update function check to see if gameOver == true and transition to the GameOverScene.
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
// Initialize _lastUpdateTime if it has not already been
if (self.lastUpdateTime == 0) {
self.lastUpdateTime = currentTime
}
// Calculate time since last update
let dt = currentTime - self.lastUpdateTime
// Update entities
for entity in self.entities {
entity.update(deltaTime: dt)
}
self.lastUpdateTime = currentTime
if gameOver == true {
print("Game Over!")
let nextScene = GameOverScene(size: self.scene!.size)
nextScene.scaleMode = self.scaleMode
nextScene.backgroundColor = UIColor.black
self.view?.presentScene(nextScene, transition: SKTransition.fade(with: UIColor.black, duration: 1.5))
}
}
The update function will check at each frame render to see if the game is over and if it is found to be over it will perform any actions that you need it to and then present the next scene.
Then on the GameOverScene I put a button saying "Retry" and when they click that it fires off the GamePlayScene again, running the view DidLoad function and setting up the GamePlayScene from scratch the way that it should.
Here is an example of how I handle that. There are a few different ways to call a scene transtion. You can give this one a try if it isn't working quite right.
if node.name == "retryButton" {
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view! as 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
scene.size = skView.bounds.size
skView.presentScene(scene, transition: SKTransition.fade(withDuration: 2.0))
}
}
That is my preferred method of handling the game over transitions.
The other method would be to create a function that resets all of the variables that have changed during the course of playing. Then you could use the same code from the Update function above, but instead of transitioning you could create a label on the scene. If the user clicks the label it would fire off of that function to reset all of the variables that have changed, reset the players locations, stops all actions, resets players health etc. Depending on how many things you have changing during the course of gameplay it'll probably be more practical, (as I've found), to transition to a new scene to give a summary and then reload the GamePlayScene through a button. Then everything will load up just the same as it does the first time that the user entered that main GamePlayScene.

How to add an overlay start scene in swift?

can someone code for me please how to add an overlay start scene in swift?
I want to add a startMenu like in Flappy Bird, and then when you click play it just moves/fades away and the game begins.
Can someone help me achieve this effect?
Looking to achieve this.
I will be more than thankful!
Try to post some code of what you have tried so far when asking a question on stack overflow, people tend to not write code for you.
You can basically do this 2 ways.
1)
Either create a StartScene and transition to GameScene with your preferred SKTransition when the play button is pressed e.g SKTransition.crossFade
2)
If you want to do it in the same scene you can just create a SKNode/SKSpriteNode class to use as a menu.
class Menu: SKSpriteNode {
lazy var playLabel: SKLabelNode = {
let label = SKLabelNode(fontNamed: "HelveticaNeue")
label.text = "Play"
label.fontSize = 22
label.fontColor = .yellow
label.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
return label
}()
/// Init with size
init(size: CGSize) {
super.init(texture: nil, color: .red, size: size)
addChild(playLabel)
}
}
}
Than in your GameScene Scene you can add the menu like so with your preferred size, in this example the size of the scene.
class GameScene: SKScene {
lazy var menu: Menu = Menu(size: self.size)
override func didMove(to view: SKView) {
addChild(menu)
}
}
You can add other nodes for UI, including sprites for buttons etc, to that menu class.
Than in GameScene in touches Began you can look for nodes that are touched, e.g the play button and than do your thing e.g to animate out the menu
let action1 = SKAction.fadeAlpha(to: 0, duration: 0.5)
let action2 = SKAction.removeFromParent()
let sequence = SKAction.sequence([action1, action2])
menu.run(sequence)
If you stuck there and want more coding samples you should google how to do this, is basic SpriteKit stuff that you need to know and there is plenty tutorials available. This includes samples of how to make button subclasses using SKSpriteNodes.
Hope this helps

swift/spritekit: Is there a way to add a SKLabelNode to an SKView?

I'm trying to create a hud that sits at the top of the screen and doesn't move with the rest of the scene. I was able to get a static view up there with this:
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let hud = SKView()
hud.alpha = 0.5
hud.backgroundColor = SKColor.greenColor()
hud.frame = CGRect(x: 0.5, y: 0.5, width: view.bounds.width, height: 50)
self.view?.addSubview(hud)
So with that, my player can walk around the scene, the camera follows him, but there is always a transparent view across the top which is what I think I want.
So next I tried adding things to the hud view at the top but I can't seem to figure it out. For example, if I create an SKLabel node I can't add it with hud.addChild because SKView doesn't have addChild. I tried doing hud.addSubview but a SKLabel isn't a UIView, which is what addSubview expects.
Does anyone know how I add things to the hud like labels?