Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make SKSpriteNode subclass using Swift

I'm trying to create class which is a subclass of SKSpriteNode and I want to add other properties and functions to it. But in the first step I faced an error. Here's my code:

import SpriteKit

class Ball: SKSpriteNode {
    init() {
        super.init(imageNamed: "ball")
    }
}

It's not a compile error, It's run-time error. It says: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) and fatal error: use of unimplemented initializer 'init(texture:)' for class Project.Ball.

How can I fix it?

like image 289
Potter Avatar asked Aug 20 '14 06:08

Potter


1 Answers

You have to call the designated initializer for SKSpriteNode. I'm actually surprised you didn't get another error about not full implementing SKSpriteNode, are you using an older Xcode6 beta maybe?

Since you have to use the designated initializer, you need to call super.init(texture: '', color: '', size: '').

It would be something like this:

class Ball: SKSpriteNode {
    init() {
        let texture = SKTexture(imageNamed: "ball")
        super.init(texture: texture, color: nil, size: texture.size())
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Note: I also added the init for NSCoder which Xcode will require.

like image 177
Mike S Avatar answered Nov 10 '22 01:11

Mike S