Subclassing with custom initializer from .sks file - sprite-kit

I have a custom class and I create nodes in the .sks file that I want to be instances of that custom class using a custom initializer.
custom class:
Class Enemy: SKSPritenode {
init(name: String, image: String, health: Int) {
// stuff here
}
}
SKScene:
// error at runtime:
var enemy1 = childNodeWithName("Enemy1") as! Enemy
// error:
var enemy1 = childNodeWithName("Enemy1") as! Enemy(name: "enemy1, image: "enemy1", health: 100)
Is there a way to use the custom initializer with the .sks file?

Associating your Custom Class to a Node
If you want to associate a node you create into your SKS file to a custom class, you need to:
Add an empty node into your SKS file
Select the Node
Open the Custom Class inspector in Xcode
Type the name of your class into the Custom Class field
Type the name of your project into the Module field
Using the right initializer
When SpriteKit does load the SKS file and start building the objects to populate the scene it does not call you custom initializer but this one
required init?(coder aDecoder: NSCoder)
so your Enemy class should be defined like this
class Enemy: SKSpriteNode {
let health: Int
required init?(coder aDecoder: NSCoder) {
self.health = 10
let texture = SKTexture(imageNamed: "Spaceship")
super.init(texture: texture, color: .clearColor(), size: texture.size())
}
}
Test
You can now test that you have a real Enemy object into your scene defining this method into your GameScene
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let enemy = (children.filter { $0 is Enemy }).first else { fatalError("No Enemy found") }
print(enemy)
}
Using your custom initializer
Right now there is no way of passing parameter from the SKS file to your custom initializer.
However such a technique was available into CocosBuilder, an old Game Level editor available for Cocos2d so I believe sometime in the future we will be able to pass parameters from the SKS file to our custom classes.
Maybe this will be announced with the next version of SpriteKit in a few days during the WWDC 2016.

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.

Editing properties of an SKSpriteNode custom class?

In my custom SKSpriteNode class, I want to be able to change properties such as anchorPoint, posistion, etc. within the custom class so I don't need to elsewhere.
import Foundation
import SpriteKit
open class Crank:SKSpriteNode {
init() {
super.init(texture: SKTexture(imageNamed: "crank"), color:
NSColor.white, size: CGSize(width: 155.0, height: 188.0))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
How would I edit other properties?
import Foundation
import SpriteKit
class Crank: SKSpriteNode {
init(imageNamed image: String, position at: CGPoint, withAnchor anchor: CGPoint) {
super.init(imageNamed: image)
self.position = position
self.anchorPoint = anchor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
(Written from memory, so may contain small errors, but is broadly correct).
and then in your main code:
let myCrank = Crank(imageNamed: "Crank.png", at: CGPoint(300, 500), withAnchor: CGpointZero)
My answer notwithstanding, Alessandro has a point. I think that it's better to set 'standard' properties in the normal place.
If you are going to set any of the standard SKSpriteNode properties inside the actual class, then I think specifying them in an initialiser is good practice as it makes the m more visible,. Debugging a program where you don't appears to set a node's position, or texture etc. would be problematic.
Another way to do it would be to create a protocol and apply it to the standard SpriteKit classes that you are subclassing (or their ancestor).
For example:
protocol CustomSKNode
{
var position:CGFloat { get set }
var zRotation:CGFloat { get set }
// ...
}
extension SKNode: CustomSKNode {}
Once you've done this somewhere in your project, you'll be able to access these properties of on any of your custom SKNode or SKSpriteNode without having to import SpriteKit.

SpriteKit custom subclass inside reference node init(coder:) called multiple times for single object

My SKScene (GameScene) is initialised from an '.sks' file called 'GameScene', which contains just an 'SKReferenceNode' to another sks file called 'Tank'
'Tank.sks' contains an SKNode which has the custom class 'Tank':
In the class definition for 'Tank' I defined 'init(coder:)' like so:
class Tank: SKNode {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
print("setup")
}
}
When I run the project, 'setup' is output three times (even though there should only be one tank object').
I checked that there is only one Tank object like so:
override func didMove(to view: SKView) {
enumerateChildNodes(withName: "//*") { (node, _) in
if node is Tank {
print("found a tank")
}
}
}
but 'found a tank' is only printed once.
Why is this, and is there another method I can use to setup my 'Tank' which is only called once when the Object is unarchived and ready for use (similar to 'didMoveToView' for SKScene.

Is it possible to add a SKSpriteNode to a scene from another class?

Is it possible to add a SKSpriteNode to a scene from another class?
*These are examples
So I have a SKScene with a custom class ..
class MainMenu: SKScene {
code...
}
And another SKScene with a custom class ..
class GameOver: SKScene {
code...
}
I have another class called PopupMenu ...
class PopupMenu: SKScene {
func addSprite() {
theSprite = SKSpriteNode.init(imageNamed: "theImage")
theSprite.position = CGPointMake(self.frame.width/2, self.frame.height/2)
theSprite.zPosition = 2
self.addChild(theSprite)
}
So what I am trying to achieve is to be able to click the show menu button on both the MainMenu Scene and the GameOver Scene and be able to call the function from PopupMenu to add that node to the respective scene.
I can achieve this by writing the code for the popup in each Scene Class but i feel like this is not the best way to do it in terms of reusability.
Is there a better way to do this?
Look into SKReferenceNodes, you can create your popup menu via the SpriteKit Scene Builder, then save this as an sks file. When it comes time to use it, you just pull up the file of the popup menu, and add it to the scene.
Source: https://developer.apple.com/reference/spritekit/skreferencenode
Another thing you can do if you plan on not using the SKS Builder (Which I recommend using because it is just awesome and a huge time saver), is to subclass your pop up menu as an SKSpriteNode, not a scene
class PopupMenu: SKSpriteNode {
required init?(coder: aDecoder:NScoder) {
super.init(coder:aDecoder)
}
override init(texture: SKTexture!, color: SKColor!, size: CGSize) {
super.init(texture: texture, color: color, size: size) {
}
convenience init() {
self.init(imageNamed: "theImage")
self.zPosition = 2
}
}
Then in your scene code, just call
let popup = PopupMenu()
popup.position = CGPointMake(self.frame.width/2, self.frame.height/2)
self.addChild(popup)
If you want your game works well, the first thing to do is to make sure that, when you pass to a new scene, the previous scene is deallocated.
I think you can construct a common menu or a common menu button to a custom class and call it anywhere you want:
class MenuButton : SKSpriteNode
{
var length: CGFloat!
override init(texture: SKTexture!, color: SKColor!, size: CGSize) {
self.length = 50 // default lenght
super.init(texture: texture, color: color, size: size)
}
convenience init(color: SKColor, length: CGFloat = 50) {
var size = CGSize(width: length, height: length);
self.init(texture:nil, color: color, size: size)
self.length = length
}
required init?(coder aDecoder: NSCoder) {
// Decoding length here would be nice...
super.init(coder: aDecoder)
}
}

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.