Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SKSpriteNode subclassing swift

I have found a few posts on this but I'm still confused on how to do this. I know I have to use the "designated initializer" which is the init(texture: SKTexture!, color: UIColor!, size: CGSize). Really I won't use that anyway. I'd like to just add some properties to the sprite nodes.

class Piece: SKSpriteNode {

enum Type: Int {
    case type1 = 1, type2, type3, type4, type5
}

    var piecetype : Type 

init(texture: SKTexture!, color: UIColor!, size: CGSize)
{
    self.piecetype = .type1
    super.init(texture: texture, color: color, size: size)

}


convenience init(imageNamed: String!, currentPiece: Type)
    {
        self.piecetype = currentPiece
        let color = UIColor()
        let texture = SKTexture(imageNamed: imageNamed)
        let size = CGSizeMake(100.0, 100.0)
        super.init(texture: texture, color: color, size: size)
    }

in the main code I try to add a piece by using

var newPiece : Piece = Piece(imageNamed: "image.png", currentPiece: .type1)
self.addChild(newPiece)

It seems like I'm close, but I'm a bit confused on how to do the initializers.

like image 885
Cherr Skees Avatar asked Feb 13 '23 09:02

Cherr Skees


1 Answers

Just change your convenience initializer to this:

convenience init(imageNamed: String!, currentPiece: Type) {
    let color = UIColor()
    let texture = SKTexture(imageNamed: imageNamed)
    let size = CGSizeMake(100.0, 100.0)
    self.init(texture: texture, color: color, size: size)
    self.piecetype = currentPiece
}

In Swift, a convenience initializer must:

  • Call another convenience initializer of the same class or the designated initializer of the class (not the superclass)
  • Use self only after calling self.init[...]

See the Swift Documentation on initializer for help: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_323

Hope this helps,

like image 70
Zedenem Avatar answered Feb 26 '23 21:02

Zedenem