Caractacus
Caractacus

Reputation: 83

Am unable to subclass SKSpriteNode using an image name

I am having trouble subclassing SKSpriteNode when I need to use an .png image and all the help I can find on Google only mentions SKTexture.

In my regular class this code works:

let circle = SKSpriteNode(imageNamed: "slot")
circle.setScale(1.0)
circle.anchorPoint = CGPoint(x: 0, y: 0.5)
circle.position = CGPoint(x: 1000, y: 500)
self.addChild(circle)

I would like to move it to a subclass, but no matter what combination I try am always getting errors such as:

Cannot convert value of type 'SKTexture' to expected argument type 'String'

or

Must call a designated initializer of the superclass 'SKSpriteNode'

I am able to subclass SKSpriteNode if I want to use SKTexture. Yet at this juncture the init I want to subclass is SKSpriteNode(imageNamed: String)

Here is what I am trying to do, but of course I get errors

class MyBall : SKSpriteNode{
    init(iNamed: String){
        super.init(imageNamed: iNamed)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Upvotes: 2

Views: 137

Answers (1)

Ron Myschuk
Ron Myschuk

Reputation: 6061

Just use the full initializer on the super, like so...

class MyBall : SKSpriteNode{

    init(iNamed: String) {
        let texture = SKTexture(imageNamed: iNamed)
        super.init(texture: texture, color: .clear, size: texture.size())
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Upvotes: 3

Related Questions