super.init() recursive issue in Swift - swift

I am working on a SpriteKit game using Swift and I need to subclass SKSpriteNode. In the init() (which is not an override) function I initialize the subclass's properties then call the super:
init(selector: Selector, delegateScene: SKScene, text: String, position: CGPoint) {
self.delegateScene = delegateScene
self.labelNode = SKLabelNode()
self.labelNode.position = CGPointZero
self.labelNode.text = text
self.selector = selector
super.init()
}
I set a breakpoint at the super.init() and a EXC_BAD_INSTRUCTION exception occurs right after it at the beginning of the subclass's init. Here's the error:
(file path).swift: 12: 7: fatal error: use of unimplemented initializer 'init(texture:color:size:)' for class 'Energies.Button'

If you inherit from SKSpriteNode, you should call the designated initializer. In this case that needs to be init(texture:color:size:). So if you were using a image or texture, you would need to call super.init like this:
super.init(texture: texture, color: nil, size: CGSize(width: 100, height: 100))
Note that you'll also need to set a size when initializing.
But in this case you can forget the above, because you're not looking for a subclass of SKSpriteNode, but a subclass of SKNode. If you change the superclass in the declaration from SKSpriteNode to SKNode it should work immediately.
You'll also need to add your add your label to the node after super.init(), else your label wouldn't be shown and your node would be empty.

Related

How do you add a child of a custom class to GameScene?

I have a custom class named Test that extends SKShapeNode with 4 SKShapeNodes as its child, and I would like to add them as a child of GameScene. However, when I try to execute addChild() in GameScene, I end up getting the error signal SIGABRT.
In my custom class I declare:
let shapeR = SKShapeNode()
let shapeG = SKShapeNode()
let shapeY = SKShapeNode()
let shapeB = SKShapeNode()
Then in override init(), I call the addChild() methods:
addChild(shapeR)
addChild(shapeG)
addChild(shapeY)
addChild(shapeB)
Finally in GameScene, I iterate through the children with (test is defined as Test()):
for child in test.children {
addChild(child)
}
How do I fix this?
Edit: I need 4 SKShapeNodes since I want 4 different colors in my custom SKShapeNode object.
Nevermind I just had to addChild() the entire class and not just separate SKShapeNodes

Using properties of SKSpriteNode for subclass

this is more of a general question about subclasses and inheritance within Swift 4.
In Apple's developer guide, a subclass ("anySubclass") of a custom class ("anySuperclass") can directly access/inherit the parent's properties, e.g.:
anySubclass.anyProperty = xyz (anyProperty was only defined within the Superclass)
To my question:
I'm currently working on my first game using SpriteKit and wanted to create subclasses of SKSpriteNode, one of which should be clBackGround.
If I just define it as a subclass of SKSpriteNode, i.e.
class clBackGround:SKSpriteNode {
}
I would think that I could simply use all properties associated with SKSpriteNode just like this:
var bg1 = clBackGround()
bg1.size = ...
.
.
.
This does not seem to be working however. So my questions is:
Do I need to initialize all the properties of SKSpriteNode I want to use within clBackGround (using a designated initializer)? How can I then assign an image to an instance of this subclass?
Any help would be much appreciated!
Not sure if this is what you're asking, but, generally, if you create a subclass of an object, you don't need to do anything special to access the superclass's properties. They'll be initialized in the usual fashion.
However, you DO have to ensure that the superclass's initializers get called in a proper manner if you have your own initializers for your subclass.
In the case of a subclass of SKSpriteNode, if you define your own initializer for the subclass, that initializer will need to call the designated superclass initializer, which passes in the texture, color, and size to use for the sprite:
init(enemyType:String) {
let texture = SKTexture(imageNamed: "enemy_\(enemyType)")
let color = UIColor.black
let size = texture.size()
super.init(texture: texture, color: color, size: size)
}

Circling the drain of Initialization in subclass: Swift and SpriteKit

I want to create a SKShapeNode at a higher level than the touchesBegan of a SpriteNode so when I want to add the SKShapeNode to the screen from the touchesBegun event on this sprite, the shape already exists, and I simply add it to the screen from within the touchesBegan override.
TL;DR, in my SKSpriteNode, I'm trying to pre-build the SKShapeNode that will be used as an animated ring when the Sprite is touched.
I'd like to create the SKShapeNode with variable/constants, so I can easily edit its values...
So in the root of the subclass I have variables for color, size, and linewidth, ready to be used in the creation of the SKShapeNode...
class Balls: SKSpriteNode {
var ringSize: CGFloat = 64
var ringColor: SKColor = SKColor.white
var ringWidth: CGFloat = 16
....
Further down, but still at the root of the class, I create my ring:
let ring = SKShapeNode(circleOfRadius: ringSize)
And am instantly greeted with the lovingly cryptic:
Can not use instance member 'ringSize' within property initializer,
property initializers run before 'self' is available.
Fine. Ok. I get it. You want to think that a functional call to a class to create a property should be done before values are assigned to self. Neither here nor there, I think I'm getting cunning and can get around that by wrapping everything in a function:
class Balls: SKSpriteNode {
var ringSize: CGFloat = 64
var ringColor: SKColor = SKColor.white
var ringWidth: CGFloat = 16
var myRing = SKShapeNode()
func createRing() -> SKShapeNode{
let ring = SKShapeNode(circleOfRadius: ringSize)
ring.strokeColor = ringColor
ring.lineWidth = ringWidth
return ring
}
This generates no errors, and my excitement builds.
So I add another line, to create the actual ring:
....
myRing = createRing()
Dead again:
! Expected
declaration
I have absolutely no idea what this means and began to randomly attempt weird things.
One of them is heading into my already messy convenience initializer and adding myRing = createRing() in there... and this WORKS!
How and why does this work, and is this the best/right/proper way to be circling the drain of initialization?
:: EDIT:: UPDATE :: Full Code Context ::
Here's the full class with my bizarre and misunderstood initialisers.
import SpriteKit
class Circle: SKSpriteNode {
var ringSize: CGFloat = 96
var ringColor: SKColor = SKColor.white
var ringWidth: CGFloat = 8
var myRing = SKShapeNode()
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init() {
self.init(color: SKColor.clear, size: CGSize(width: 100, height: 100))
myRing = createRing()
addChild(myRing)
print("I'm on the screen")
explodeGroup = create_explosionActionGroup()
}
convenience init(color: UIColor, size: CGSize, position: CGPoint) {
self.init(color: color, size: size)
self.position = position
myRing = createRing()
explodeGroup = create_explosionActionGroup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createRing() -> SKShapeNode{
let ring = SKShapeNode(circleOfRadius: ringSize)
ring.strokeColor = ringColor
ring.lineWidth = ringWidth
return ring
}
Your createRing() method is inside Ball class so you need to create an instance of Ball first.
Simple way - You can change creation of instance to
let ball = Balls()
let myRing = ball.createRing()
I'm slightly confused as to where you placed the
myRing = createRing()
line of code but I'm wondering if this setup would help solve your problem
lazy var myRing: SKShapeNode = {
let ring = SKShapeNode(circleOfRadius: ringSize)
ring.strokeColor = ringColor
ring.lineWidth = ringWidth
return ring
}()
This way myRing would be created when it was accessed which should be after the Balls class is instantiated which would mean that ringSize, ringColor and ringWidth would all exist.
Based on your update I think your best bet might be to just make your three ring variables ‘static let’ instead. That way they will exist and have the set value before initializing the main class. The errors you’re seeing are because you created instance variables. Those will only exist when the instance has been initialized. So if you tried to call the ring method as the declaration of the variable or if you did it within the init before self/super init is called then the instance variables wouldn’t be accessible. The most recent code you’ve added should be working because you create the instance before attempting to generate the ring. I hope that makes sense and helps.
And am instantly greeted with the lovingly cryptic:
Can not use instance member 'ringSize' within property initializer, property initializers run before 'self' is available.
So one way around this problem would be to make the default ringSize available another way, e.g.
static let defaultRingSize: CGFloat = 64
var ringSize: CGFloat = Circle.defaultRingSize
let ring = SKShapeNode(circleOfRadius: Circle.defaultRingSize)
... but I question why you even have a var ringSize property like that. Shouldn't you have a didSet observer on it, so that if you change its value, you can update the shape of ring?
Dead again:
! Expected declaration
You weren't clear, in your question, how you actually triggered this, but I guess you tried something like this:
class Circle: SKSpriteNode {
var ringSize: CGFloat = 96
var myRing = SKShapeNode()
myRing = createRing() // “Expected declaration” error on this line
The problem here is that you've placed a statement in the body of your class, but only declarations are allowed in the body.
One of them is heading into my already messy convenience initializer and adding myRing = createRing() in there... and this WORKS!
How and why does this work
All of your class's own instance variables must be initialized before a super.init call. Since myRing has a default value, the compiler effectively inserts the initialization of myRing before the call to super.init in your designated initializer, like this:
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
// Compiler-inserted initialization of myRing to the default
// value you specified:
myRing = SKShapeNode()
super.init(texture: texture, color: color, size: size)
}
Since you declared var myRing, you can then change it later to the customized SKShapeNode you really want.
is this the best/right/proper way to be circling the drain of initialization?
Well, “circling the drain” means “failing”, so I guess you're asking if this is “the best/right/proper way” to fail at initialization… I suppose it's not the best way to fail, since you didn't actually fail in the end.
Or maybe you meant “I hate the way Swift does initialization so I'm going to throw some shade”, in which case, you ain't seen nothin' yet.
But maybe you really meant “is this the best/right/proper way to initialize my instance”, in which case, well, “best” and “right” and “proper” are pretty subjective.
But I can objectively point out that you're creating an SKShapeNode (as the default value of myRing) just to immediately throw it away and create another SKShapeNode. So that's a waste. You've also got calls to createRing in both of your convenience initializers, but you could factor them out into the designated initializer.
But I wouldn't even do it quite like that. SKShapeNode's path property is settable, so you can just create a default SKShapeNode and then change its path after the call to super.init. That also makes it easier to handle changes to ringSize and the other properties, because you can funnel all the changes through a single method that knows how to make myRing match the properties.
Here's how I'd probably write your class:
import SpriteKit
class Circle: SKSpriteNode {
var ringSize: CGFloat = 96 {
// Use an observer to update myRing if this changes.
didSet { configureMyRing() }
}
var ringColor = SKColor.white {
didSet { configureMyRing() }
}
var ringWidth: CGFloat = 8 {
didSet { configureMyRing() }
}
// This can be a let instead of a var because I'm never going to
// set it to a different object. Note that I'm not bothering to
// initialize myRing's path or any other property here, because
// I can just call configureMyRing in my init (after the call to
// super.init).
let myRing = SKShapeNode()
override init(texture: SKTexture?, color: SKColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
// Call this now to set up myRing's path and other properties.
configureMyRing()
}
convenience init() {
self.init(color: SKColor.clear, size: CGSize(width: 100, height: 100))
// No need to do anything to myRing now, because my designated
// initializer set it up completely.
addChild(myRing)
print("I'm on the screen")
// Commented out because you didn't provide this property
// or method in your question.
// explodeGroup = create_explosionActionGroup()
}
convenience init(color: SKColor, size: CGSize, position: CGPoint) {
self.init(color: color, size: size)
self.position = position
// Commented out because you didn't provide this property
// or method in your question.
// explodeGroup = create_explosionActionGroup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureMyRing() {
myRing.path = CGPath(ellipseIn: CGRect(x: -ringSize / 2, y: -ringSize / 2, width: ringSize, height: ringSize), transform: nil)
myRing.strokeColor = ringColor
myRing.lineWidth = ringWidth
}
}

Creating and Using Classes

If I create an instance of the class below and call the spawn function from my controller, the sprite will appear but I won't be able to change any of its properties.
class Hero: SKSpriteNode
{
var hero = SKSpriteNode(imageNamed: "hero3")
func spawn(parentNode: SKNode, position: CGPoint, size: CGSize = CGSize(width: 50, height: 50))
{
hero.size = size
hero.position = position
hero.physicsBody = SKPhysicsBody(circleOfRadius: 25)
hero.physicsBody?.allowsRotation = false
hero.zPosition = 10
parentNode.addChild(hero)
}
}
If I get rid of the hero property and change everything to self, it works fine.
class Hero: SKSpriteNode
{
func spawn(parentNode: SKNode, position: CGPoint, size:CGSize = CGSize(width: 50, height: 50))
{
self.size = size
self.position = position
self.texture = SKTexture(imageNamed: "hero3")
self.physicsBody = SKPhysicsBody(circleOfRadius: 25)
self.physicsBody?.allowsRotation = false
self.zPosition = 10
parentNode.addChild(self)
}
}
I'm sure this is swift 101, but can someone please explain why the first version doesn't work as expected?
In your first example, you created a var (basically a SpriteNode inside the SpriteNode).
When you instantiate the class like let hero = Hero(....) you now have a SpriteNode called hero, with a property called hero. You can change either. Calling hero.size would change the base hero, and hero.hero.size would change the inside SpriteNode....this is probably not the behavior you were looking for.
The second class looks correct, if you are just trying to create a SpriteNode and modify it. The class is a subclass of SpritNode, so it's already a SpriteNode - no need to create one inside it like the first one.
Hope this helps!
Your Hero class inherits from SKSpriteNode, so it is essentially an SKSpriteNode already, which means you don't need to create a hero SKSpriteNode variable.
In your first class, when you use hero.size = size, you're accessing the properties of the variable within your class instead of on the class itself. Then you add the hero SKSpriteNode as a child along with all its properties, but your class SKSpriteNode, which holds the variable doesn't have set properties size or a physics body. You can think of the class as a container that's holding the variable SKSpriteNode.
In your second function, when you use self.size = size, you're accessing the class's properties and giving the class SKSpriteNode all the properties you need to use it in other classes.

SubClassing a sub-class in swift (skspritenode)

I'm currently making a game that will have multiple types of enemies, I currently made the basic enemy using a subclass of SKSpriteNode and everything is working fine. I now want to implement another sub class of the basic enemy since all the enemies are similar. I am having trouble creating the new subclass. Any help would be much appreciated. Here is my code...
class Basic_Fighter : SKSpriteNode {
var health : Int = 3
var ship_speed : Double = 7.0
var bullet_rapidness : Double = Double ((arc4random_uniform(3) + 2) )
var bullet_speed : Double = 3.0
var action = SKAction()
var bullet_Timer : NSTimer?
func subtract_health(){ health-- }
func enemy_killed(){
let action = SKAction.moveToY(-1000, duration: 5)
self.runAction(SKAction.repeatActionForever(action))
let rotateAction = SKAction.rotateByAngle(CGFloat(M_PI), duration: 3)
self.runAction(SKAction.repeatActionForever(rotateAction))
//Set a timer to destoy the node
_ = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("destroy"), userInfo: nil, repeats: false)
}
func destroy(){
self.removeFromParent()
}
}
and the next enemy ....
class new_fighter : Basic_Fighter {
convenience init(){
self.init()
health = 5
}
}
I am not sure which exactly question are you asking, but this part is wrong:
class new_fighter : Basic_Fighter {
convenience init(){
self.init()
health = 5
}
}
You can not have convenience initializer declared just as is, without a designated initializer. Perhaps you should revisit Swift language reference for the part about designated vs. convenience initializers.
From the documentation:
... Swift applies the following three rules for delegation calls between initializers:
Rule 1
A designated initializer must call a designated initializer from its immediate superclass.
Rule 2
A convenience initializer must call another initializer from the same class.
Rule 3
A convenience initializer must ultimately call a designated initializer.
When you subclass SKSPriteNode you must use this designated initializer:
init(texture: SKTexture?, color: UIColor, size: CGSize)
and in your convenience initializer call: self.init(texture: texture, color: color, size: size)