how to add a sprite an existing scene - swift

What is the best way to add a sprite node after a scene has been fully loaded? The sequence looks like this:
1) I build the scene, GameScene().
2) Some time later, I download backend data and I use this info to build a SKSpriteNode in a different class, NodeBuilder().
3) I want to add this node to the instance of my scene that I'd already loaded.
What's the best way to achieve step 3)?

In GameScene:
addChild(yourNode)
For getting and keeping a reference to NodeBuilder:
Creation of NodeBuilder in GameScene:
class GameScene : SKScene {
var nodeBuilder = NodeBuilder() // Create an instance of NodeBuilder
func didMoveToView(skView: SKView) {
nodeBuilder.gameScene = self // Add self as the instance of GameScene that nodeBuilder has reference to
}
}
In NodeBuilder:
class NodeBuilder {
var gameScene : GameScene! // This is how you keep your reference
func addNodeToGameScene(node: SKNode) {
self.gameScene.addChild(node)
}
addNodeToGameScene(aNode) // This is how you would call the method to add a node to GameScene from NodeBuilder
}

Related

Use multiple classes to control a single SKScene [duplicate]

I'm trying to learn how to make a GameManager type class, and making individual classes for each of my GameScenes... probably the wrong thing to do, but for the sake of this question, please accept this as the way to do things.
My GameManager looks like this, having a reference to each of the scenes, that's static:
import SpriteKit
class GM {
static let scene2 = SecondScene()
static let scene3 = ThirdScene()
static let home = SKScene(fileNamed: "GameScene")
}
How do I create a SKScene programmatically, without size info, since they're in a subclass of SKScene and don't have any idea what the view size is, and I don't want them to need worry about this:
I'm doing this, but getting a EXC_BAD_Access at convenience override init()
class SecondScene: SKScene {
override init(size: CGSize){
super.init(size: size)
}
convenience override init(){
self.init()
self.backgroundColor = SKColor.red
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
}
}
As I mentioned your question is a bit vague but lets do some examples of what a GameManager class can be.
Before I start lets differentiate between calling this
let scene = StartScene(size: ...)
and this
let scene = SKScene(fileNamed: "StartScene")
The 1st method, with size, is when you create your scenes all in code and you are not using the xCode visual level editor.
The 2nd method is when you are using the Xcode level editor, so you would need to create a StartScene.sks file. Its that .sks file that it looks for in fileNamed.
Now for some game manager example, lets first imagine we have 3 SKScenes.
class StartScene: SKScene {
override func didMove(to view: SKView) { ... }
}
class GameScene: SKScene {
override func didMove(to view: SKView) { ... }
}
class GameOverScene: SKScene {
override func didMove(to view: SKView) { ... }
}
Lets say you want to transition from StartScene to GameScene, you would add this code in your StartScene at the correct spot e.g when the play button is pressed. Thats the simplest way to move from one SKScene to the next, directly from the SKScene itself.
// Code only, no xCode level editor
let gameScene = GameScene(size: CGSize(...))
let transition = SKTransition...
gameScene.scaleMode = .aspectFill
view?.presentScene(gameScene, transition: transition)
// With xCode level editor (returns an optional so needs if let
// This will need the GameScene.sks file with the correct custom class set up in the inspector
// Returns optional
if let gameScene = SKScene(fileNamed: "GameScene") {
let transition = SKTransition...
gameScene.scaleMode = .aspectFill
view?.presentScene(gameScene, transition: transition)
}
Now for some actual examples of GameManagers, Im sure you know about some of them already.
EXAMPLE 1
Lets say we want a scene loading manager. You approach with static methods will not work because a new instance of SKScene needs be created when you transition to one, otherwise stuff like enemies etc will not reset. Your approach with static methods means you would use the same instance every time and that is no good.
I personally use a protocol extension for this.
Create a new .swift file and call it SceneLoaderManager or something and add this code
enum SceneIdentifier: String {
case start = "StartScene"
case game = "GameScene"
case gameOver = "GameOverScene"
}
private let sceneSize = CGSize(width: ..., height: ...)
protocol SceneManager { }
extension SceneManager where Self: SKScene {
// No xCode level editor
func loadScene(withIdentifier identifier: SceneIdentifier) {
let scene: SKScene
switch identifier {
case .start:
scene = StartScene(size: sceneSize)
case .game:
scene = GameScene(size: sceneSize)
case .gameOver:
scene = GameOverScene(size: sceneSize)
}
let transition = SKTransition...\
scene.scaleMode = .aspectFill
view?.presentScene(scene, transition: transition)
}
// With xCode level editor
func loadScene(withIdentifier identifier: SceneIdentifier) {
guard let scene = SKScene(fileNamed: identifier.rawValue) else { return }
scene.scaleMode = .aspectFill
let transition = SKTransition...
view?.presentScene(scene, transition: transition)
}
}
Now in the 3 scenes conform to the protocol
class StartScene: SKScene, SceneManager { ... }
and call the load method like so, using 1 of the 3 enum cases as the scene identifier.
loadScene(withIdentifier: .game)
EXAMPLE 2
Lets make a game manager class for game data using the Singleton approach.
class GameData {
static let shared = GameData()
private init() { } // Private singleton init
var highscore = 0
func updateHighscore(forScore score: Int) {
guard score > highscore else { return }
highscore = score
save()
}
func save() {
// Some code to save the highscore property e.g UserDefaults or by archiving the whole GameData class
}
}
Now anywhere in your project you can say
GameData.shared.updateHighscore(forScore: SOMESCORE)
You tend to use Singleton for things where you only need 1 instance of the class. A good usage example for Singleton classes would be things such as helper classes for Game Center, InAppPurchases, GameData etc
EXAMPLE 3
Generic helper for storing some values you might need across all scenes. This uses static method approach similar to what you were trying to do. I like to use this for things such as game settings, to have them in a nice centralised spot.
class GameHelper {
static let enemySpawnTime: TimeInterval = 5
static let enemyBossHealth = 5
static let playerSpeed = ...
}
Use them like so in your scenes
... = GameHelper.playerSpeed
EXAMPLE 4
A class to manage SKSpriteNodes e.g enemies
class Enemy: SKSpriteNode {
var health = 5
init(imageNamed: String) {
let texture = SKTexture(imageNamed: imageNamed)
super.init(texture: texture, color: SKColor.clear, size: texture.size())
}
func reduceHealth(by amount: Int) {
health -= amount
}
}
Than in your scene you can create enemies using this helper class and call the methods and properties on it. This way you can add 10 enemies easily and individually manage their health etc. e.g
let enemy1 = Enemy(imageNamed: "Enemy1")
let enemy2 = Enemy(imageNamed: "Enemy2")
enemy1.reduceHealth(by: 3)
enemy2.reduceHealth(by: 1)
Its a massive answer but I hope this helps.

I keep getting an error saying "expected declaration"

I'm following a tutorial to make a version of flappy bird. I'm using swift and this error keeps coming up. The "addChild(self.myFloor1) keeps saying expected declaration error. What did I do wrong?
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var myBackground = SKSpriteNode()
var myFloor1 = SKSpriteNode()
var myFloor2 = SKSpriteNode()
addChild(self.myFloor1)
override func didMoveToView(view: SKView) {
myBackground = SKSpriteNode(imageNamed: "background")
myBackground.anchorPoint = CGPointZero;
myBackground.position = CGPointMake(100, 0);
self.backgroundColor = SKColor(red: 80.0/255.0, green: 192.0/255.0, blue: 203.0/255.0, alpha: 1.0)
addChild(self.myBackground)
myFloor1 = SKSpriteNode(imageNamed: "floor")
myFloor2 = SKSpriteNode(imageNamed: "floor")
myFloor1.anchorPoint = CGPointZero;
myFloor1.position = CGPointMake(0, 0);
myFloor2.anchorPoint = CGPointZero;
myFloor2.position = CGPointMake(myFloor1.size.width-1, 0);
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
When you write
addChild(self.myFloor1)
You are calling a method, which must be done inside another method declaration.
Within your class declaration, the "highest level" "things" need to be declared as something: "var", "let", "func". Then within a "func", you can call your addChild method.
That's why you are getting the error: At that "class" level, it's expecting only things that you can specify what they are. Which here, you are not. You are trying to directly call that method.
What I suspect you may want, is add the viewDidLoad method and call addChild from within there. Or something like that...whatever makes sense for your view lifecycle.
Declaration refers to creating a new variable or method. The location you wrote addChild() seems as if you're creating a new variable. For example, let's look at the following simple class.
class GameScene: SKScene {
var myBackground = SKSpriteNode()
}
The variable myBackground is being declared as a new variable. You are creating a new instance of an SKSpriteNode object. SKSpriteNode is also a class. Now let's add a method to your GameScene class that prints hello. All the things you declare in the class is referred as being in the top level, which is where you create variables and functions, etc.
class GameScene: SKScene {
var myBackground = SKSpriteNode()
//This is a method/function of the class GameScene
func sayHello() {
print("Hello.")
}
//CAN'T CALL ITS OWN METHOD AT THE TOP LEVEL
sayHello()
}
To help you understand, addChild is a method/function of the SKNode class.
class SKNode: UIResponder {
func addChild(node: SKNode) {...}
}
So when you have something like you have it, it doesn't make sense because addChild is a function and you can't call a function at the top level of a class.
class GameScene: SKScene {
var myBackground = SKSpriteNode()
var myFloor1 = SKSpriteNode()
//CAN'T CALL METHOD ON TOP LEVEL OF CLASS
addChild(self.myFloor1)
}
Xcode thinks you're creating a new function called addChild, so it's expecting you to declare it by using the "func" keyword, which is why it's giving you the error, but obviously you're not creating a function call addChild, you need to call it.
You have to call addChild() inside a function/method because it calls the SKNode's addChild method.

Reuse same sprite node within multiple scenes in sprite kit using Swift

I create sprite node in my GameScene as the following. I would like to reuse createNodeA1 or nodeA1 in other SKScene. How can I do that?
import SpriteKit
class GameScene: SKScene {
var nodeA1: SKNode!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(size: CGSize) {
super.init(size: size)
// Add sprite node to the scene
nodeA1 = createNodeA1()
addChild(nodeA1)
}
}
// Create dot 1
func createNodeA1() -> SKNode {
let spriteNode = SKNode()
spriteNode.position = CGPointMake(CGRectGetMidX(self.frame)/1.5, CGRectGetMidY(self.frame)/2.0)
let sprite = SKSpriteNode(imageNamed: "dot_1")
sprite.zPosition = 3.0
sprite.name = "A1_Broj"
spriteNode.addChild(sprite)
return spriteNode
}
}
There is a few ways to do this.
You could subclass your other scenes to be subclass of the scene with the loadNode function which gives those scenes access to that function.
I asked a question about this last year
Swift multiple level scenes
Another way that might be a bit easier if you are not comfortable with scene subclassing is to just create a subclass of the node itself.
So you create a class
enum EnemyType {
case Normal
case Special
}
class NodeA1: SKSpriteNode {
init(imageNamed: String, enemyType: EnemyType) {
let texture = SKTexture(imageNamed: imageNamed)
if enemyType == .Normal {
super.init(texture: texture, color: SKColor.clearColor(), size: texture.size())
else {
// other init
}
self.zPosition = 1
self.name = ""
// add physics body, other properties or methods for the node
}
}
Than in your SKScenes you can add the node in the init method like so
nodeA1 = NodeA1(imageNamed: "ImageName", enemyType: .Normal)
nodeA1.position = ....
addChild(nodeA1)
this way ever scene where you add the node will use the subclass and therefore include all the properties, set up etc for that node. Another benefit with subclassing is that you could loop through all your nodes using
self.enumerateChildNodesWithName...
and than call custom methods on all nodes.
If you want to subclass your scenes than you would create your baseScene
class BaseScene: SKScene {
// set up all shared stuff in didMoveToView
// have your node function here
// touches began
// physics word and contact collision
// all other stuff that needs to be shared between all level scenes
}
Than your subsequent level scenes would look something like this
class Level1Scene: BaseScene {
override func didMoveToView(view: SKView) {
super.didMoveToView(view) // This lines imports all stuff in BaseScene didMoveToView
// do level 1 specific setUps.
// you can call any function or property from BaseScene, e.g the loadNode function.
}
You than load you level scenes as usual, e.g you transition to level 1 scene and it will automatically use/have access to all the superclass methods and sprites (BaseScene).
So you never call baseScene directly, its gets called automatically.
This applies for other methods in baseScene too, so say you have a Update method in BaseScene.
override func update(currentTime: CFTimeInterval) {.... }
This will work across all your level scenes which are subclasses of BaseScene.
But what happens if you need to add some specific stuff to the update method only relevant in 1 level scene and not all level scenes?
It would be the same process, you create a new update func in the LevelScene and call super.
override func update(currentTime: CFTimeInterval) {
super.update(currentTime) // this calls the baseScene Update method
/// specific stuff for that level only
}
Super simply means the super class of the currentScene, which is BaseScene if the scene is a subclass of it.
Is this helping?
This is additional answer information in terms of subclass of the baseScene. We can create node1thru node10 all in baseScene. Then in Leve1Scene which is subclass of the baseScene, all we have to do is in didMoveToView function state node1.position = CGPointMake(....) for each node that we need in Level1Scene where we would specify node's position.
If we do not need to load all of the 10 nodes in Level1Scene, for example, let's say we don't need to load to the scene node10 we can simply in didMoveToView function just state node10.removeFromParent() and this node will not be loaded to Level1Scene but rest of 9 nodes will.
Note that this example uses only 10 nodes, but you can go with any number of nodes in your baseScene.
This way of subclassing will save you a lot repeatable code in subclasses.

SpriteKit: Add SKSpriteNodes To The View

I basically want to add a SKSpriteNode to the screen and I have no idea where the mistake it. So I include pictures of my three classes participating in this problem. I created a class for all the background stuff. There I use the function addChild() to add my 56 Nodes to the View but they do not appear on the screen. Theoretically (for me) everything should work.
Hopefully you can help me adding the Nodes to the screen!
Edit: Updated the pictures.
When you call this:
GameScene().addChild(image)
you every time inside for create the local GameScene object, add image to this object and when you move to the next iteration of the loop, this object is destroyed. In fact, after your loop thire is no one GameScene object.
Second, you don't need to use var image = SKSpriteNode() in your hintergrund object. You every time set this reference to new object.
You have the cross references in code, try to make somthing like this:
class GameScene: SKScene {
...
override func didMoveToView(view: UIView) {
hintergrund.setBackgroundForScene(self, width: screenWidht)
}
}
class hintergrund {
...
class func setBackgroundForScene(gameScene: GameScene, width: CGFloat) {
...
for (...) {
...
gameScene.addChild(image)
}
}
}

Detecting scene from viewcontroller

I am working on a game in Xcode with swift/spritekit.
I want to add the background from the GameViewController but I have different scenes with each different backgrounds: GameScene / MenuScene / MapScene.
Now how do I detect in gameviewcontroller which scene is running so that I can add the right background to it(as UIImage)?
And how do I set Z-position(Z-index) of an UIImage?
You'll have to track which scene is present yourself. Something like this:
class GameViewController {
var mapScene: SKScene?
var menuScene: SKScene?
var gameScene: SKScene?
var currentScene: SKScene?
func addBackground() {
if currentScene === mapScene {
// ...
} else if currentScene === menuScene {
// ...
} else if currentScene === gameScene {
// ...
}
}
}
If the UIImage is inside an SKNode, then you can set its zPosition property. If it's just a UIImage in normal UIKit elements, then it's implicit based on when it was added as a subview. If you want it on top, remove it from its parent and re-add it:
view.removeFromSuperview()
self.parentView.addSubview(view)
You don't need to detect which scene is running if you simply add the appropriate background image in the scene's implementation. Also, I recommend you avoid adding a UIImage to your view, since you will need to manually remove it when you transition to a new scene. I suggest you create a sprite node with the background image as its texture and add that to your scene with a negative value for its zPosition. Also, you should consider setting the "background" sprite's anchor point and position to CGPointZero.
For example, in 'didMoveToView'
let backgroundNode = SKSpriteNode(imageNamed:"MenuSceneBackground")
backgroundNode.position = CGPointZero
backgroundNode.anchorPoint = CGPointZero
backgroundNode.zPosition = -1000
addChild(backgroundNode)
EDIT: Add the following to remove the gesture recognizers as needed
override func willMoveFromView(view: SKView) {
view.removeGestureRecognizer(swipeGesture)
}