Skip to content

Instantly share code, notes, and snippets.

@retrokid
Last active September 30, 2022 06:58
Show Gist options
  • Save retrokid/a93afd14382427e9ff26f1d7f773e69d to your computer and use it in GitHub Desktop.
Save retrokid/a93afd14382427e9ff26f1d7f773e69d to your computer and use it in GitHub Desktop.
subclassing sktexture and skspritenode

swift init hell!:

  • init() can only call super.init()
  • convenience init() can only call self.init()

when init() work for you (great!):

Your super-class:

import SpriteKit

class BrickGO: SKSpriteNode {
	// create a designated initializer
    init() {
        super.init(texture: nil,
                   color: .clear,
                   size: Nodes.Bricks.size)
        self.anchorPoint = .zero
        self.position = .zero
        self.zPosition = .zero
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Your sub-class:

import SpriteKit

class BlueBrickGO: BrickGO {
    override init() {
        super.init()
        self.name = "blue"
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

when init() won't work for you :

Your super class:

import SpriteKit

class DefaultTEX: SKTexture {
    // create your custom designated convenience init
    convenience init(assetName: String) {
        self.init(imageNamed: assetName)
        self.filteringMode = .nearest
    }
    
    // a super.init() is needed because you want to use self.init(imageNamed: assetName)
    // and you can't write super call in convenience init()
    override init() {
        super.init()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Your sub-class:

import SpriteKit

class GreenBrickTEX: DefaultTEX {
    convenience override init() {
        self.init(assetName: "green_brick")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
@retrokid
Copy link
Author

retrokid commented Sep 30, 2022

also make sure you're calling your superclass not frameworks' .

if init color is purple you're not calling your superclass, you're calling apple's superclass .

Make sure it's green!

Also don't use similar naming.

Create more different name than "imageNamed:", "imageName:".

Create something like "init(texture anImageName: SKTexture)"

texture-nearest-bug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment