I am trying to initialize a custom class that inherits from SKSpriteNode. Currently the class definition looks like this
import SpriteKit
class PassengerNode: SKSpriteNode {
let passengerStart: Int = 2
let passengerDestination: Int = 0
init() {
let texture = SKTexture(imageNamed: "passenger1")
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.zPosition = 100
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateTexture(newTexture: SKTexture) {
self.texture = newTexture
}
}
I want to have passengerStart and passsengerDestination assigned to the Object, respectively to the instance of the class. And ideally these both values can be different with every instantiation.
When I instantiate the Class Object I think of something like
let newObject = PassengerNode(start: 1, destination: 0, texture: "passenger1")
But I dont get it working... How do I need to change my init?
Does someone have a helping thought?
Thanks in advance.
You have to write an init method for your subclass which takes those
three parameters:
class PassengerNode: SKSpriteNode {
let passengerStart: Int
let passengerDestination: Int
init(start: Int, destination: Int, texture: String) {
let texture = SKTexture(imageNamed: texture)
passengerStart = start
passengerDestination = destination
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.zPosition = 100
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// ... more methods ...
}
The init method must initialize the properties of the subclass and
then call super.init.
Related
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")
}
}
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")
}
}
Can anyone help me solve this issue? The error shown is being generated even though I am using the designated initializer.
class OtherOrb: SKSpriteNode {
override init() {
let texture = SKTexture(imageNamed: "Orb")
super.init(texture: texture, color: UIColor.clear, size: texture.size()){
self.position = CGPoint(x: 0.0, y: 500.0)
self.physicsBody = SKPhysicsBody(circleOfRadius: 20)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
You are getting this error because of the closure you have trailing your initialiser.
In Swift, the compiler interprets a closure directly after a method call as the final argument to said method call, and hence the error you are getting effectively says that no initialiser that includes that closure argument exists.
Furthermore, your code looks very off, and I'm not convinced it's valid Swift. What are you trying to accomplish?
Based on my suspicions, I believe your code should resemble the following:
class OtherOrb: SKSpriteNode {
init() {
let texture = SKTexture(imageNamed: "Orb")
super.init(texture: texture, color: UIColor.clear, size: texture.size())
self.position = CGPoint(x: 0.0, y: 500.0)
self.physicsBody = SKPhysicsBody(circleOfRadius: 20)
}
#available(*, unavailable)
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
#available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
That is to say that you want an initialiser with no args to be your designated initialiser.
Attempting to design a game using Sprite-Kit I found that it would be easier to create a seperate class for one of my game objects being a laser from a ship. Within that class I would have some functions maybe such as updating, shooting etc. But whenever I create another class none of the variables I make are "declared". This is my code
import UIKit
import SpriteKit
class laser: SKSpriteNode {
let laser : SKSpriteNode = SKSpriteNode(imageNamed:"playerShip")
laser.position = CGPoint(x: 100, y: 200)//This is where it says no declaration
}
This is because you need to initiate the class.
In your example you would need to do the following which would allow you instantiate a laser like this laser()
class laser: SKSpriteNode {
let laser: SKSpriteNode = SKSpriteNode(imageNamed: "playerShip")
init() {
super.init(texture: nil, color: .clear, size: laser.size)
laser.position = CGPoint(x: 100, y: 200)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
But you probably really wanted this, which allows you to instantiate a laser like this let aLaser = laser("playerShip"). Then you can change the position like this alaser.position = CGPoint(x: 100, y: 200).
This method allows you to change the sprite and position easily for different lasers. Unless your game only has one laser.
class laser: SKSpriteNode {
init(_ imageName: String) {
let texture: SKTexture = SKTexture(imageNamed: imageName)
super.init(texture: texture, color: .clear, size: texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
The update function in the class below, which is a subclass of SKSpriteNode, is supposed to change the texture of the class. According to this SO answer, updating the texture property is sufficient for changing a SKSpriteNode's texture. However, this code doesn't work.
Any ideas why?
class CharacterNode: SKSpriteNode {
let spriteSize = CGSize(width: 70, height: 100)
var level = 0
init(level: Int) {
self.level = level
super.init(texture: nil, color: UIColor.clear, size: spriteSize)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(level: Int) {
self.level = level
self.texture = textureForLevel(level: level)
}
func textureForLevel(level: Int) -> SKTexture {
return SKTexture(imageNamed: "TestTexture")
}
Your code works well. In fact this SO answer is correct.
About SKSpriteNode subclass, the update method is a new custom function added by you, because the instance method update(_:) is valid only for SKScene class, this just to say that this function is not performed if it is not called explicitly.
To make a test about your class you can change your code as below( I've changed only textureForLevel method only to make this example):
class CharacterNode: SKSpriteNode {
let spriteSize = CGSize(width: 70, height: 100)
var level = 0
init(level: Int) {
self.level = level
super.init(texture: nil, color: UIColor.clear, size: spriteSize)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(level: Int) {
self.level = level
self.texture = textureForLevel(level: level)
}
func textureForLevel(level: Int) -> SKTexture {
if level == 3 {
return SKTexture(imageNamed: "TestTexture3.jpg")
}
return SKTexture(imageNamed: "TestTexture.jpg")
}
}
class GameScene: SKScene {
override func didMove(to view: SKView) {
let characterNode = CharacterNode(level:2)
characterNode.update(level:2)
addChild(characterNode)
characterNode.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
characterNode.run(SKAction.wait(forDuration: 2.0), completion: {
characterNode.update(level:3)
})
}
}
As you can see when you launch GameScene a characterNode sprite will be shown in the center of the screen. After 2 seconds, the texture will change.
I'm struggling to understand how class initialisation works. From looking at solutions to other problems I have this as an example of the classes in my app.
import Foundation
import SpriteKit
class Ground : SKSpriteNode {
override init(texture: SKTexture!, color: SKColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
self.zPosition = -20
self.name = "Ground";
}
func configure (size: CGSize, position: CGPoint) {
self.size = size
self.position = position
// Set up the Physics
self.physicsBody = SKPhysicsBody(rectangleOf: size)
self.physicsBody?.contactTestBitMask = PhysicsCategory.Player
self.physicsBody?.categoryBitMask = PhysicsCategory.Ground
self.physicsBody?.collisionBitMask = PhysicsCategory.All
self.physicsBody?.affectedByGravity = false
self.physicsBody?.allowsRotation = false
self.physicsBody?.isDynamic = false
self.physicsBody?.mass = 1.99999
}
convenience init(color: SKColor, isActive: Bool = false) {
let size = CGSize(width: 10, height: 10);
self.init(texture:nil, color: color, size: size)
}
required init?(coder aDecoder: NSCoder) {
// Decoding length here would be nice...
super.init(coder: aDecoder)
}
}
I've put the 'configure' function as a kludge fix to let me pass the scene to the class so I can set sizes depending on the size of the device screen. Ideally I would like to just pull this information on initialisation but everything I try throws up errors that I don't understand.
Im not sure which way would be correct but I was wondering firstly, how would I pass arguments to the class to start with.. e.g..
let myClass = Ground(scene: self)
or can I somehow pull the scene information from directly within the class? I can pass info into functions/methods as I did with 'configure' but I couldn't get it to work on initialisation which would certainly be cleaner.
How would you guys do it?
Size
You should not programmatically change the size of a sprite depending on the current device, just use the same size and then let SpriteKit resizing it for you.
Loading from .sks
This initializer
init?(coder aDecoder: NSCoder)
is used when the Sprite is loaded from a .sks file. However in Xcode 7 you cannot pass values from the .sks to the sprite to set the attributes. I'm not sure you are using a .sks file so for now I am just throwing a fatal_error here. In Xcode 8 however you will be able to pass values from the .sks file to your own class.
required init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
Scene
You don't need to pass a reference of the current scene to your class. Every SKNode has the scene property, just use it to retrieve the scene where the node lives. Of course keep in mind that if you invoke .scene before the node has been added to a scene it will returns nil.
Code
This is the final code
class Ground : SKSpriteNode {
init(color: SKColor = .clearColor(), isActive:Bool = false) {
let texture = SKTexture(imageNamed: "ground")
super.init(texture: texture, color: color, size: texture.size())
self.name = "Ground"
self.zPosition = -20
let physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
physicsBody.contactTestBitMask = PhysicsCategory.Player
physicsBody.categoryBitMask = PhysicsCategory.Ground
physicsBody.collisionBitMask = PhysicsCategory.All
physicsBody.affectedByGravity = false
physicsBody.allowsRotation = false
physicsBody.dynamic = false
physicsBody.mass = 1.99999
self.physicsBody = physicsBody
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
}
Unless I'm missing something else you're trying to do, you should be able to move the initialization of the PhysicsBody and the other properties from you configure() method and into your init() for the class. Then you can pre-size the texture you pass in on instantiation to result in the proper size for the device.
Also, the position property of the SKSpriteNode can be set by the instantiating class. This means you can accomplish the sizing based on device and the setting of the position property right after instantiating it in your scene and before adding it as a child of the scene.
ADDED:
class Ground : SKSpriteNode {
override init(texture: SKTexture!, color: SKColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init(texture: String, scene: SKScene, isActive: Bool = false) {
let texture = SKTexture(imageNamed: "\(yourtexturename)")
self.init(texture:teture, color: color, size: scene.size)
self.size = size
self.position = [YOU CAN NOW SET POSITION BASED ON THE SCENE]
self.physicsBody = SKPhysicsBody(rectangleOf: size)
self.physicsBody?.contactTestBitMask = PhysicsCategory.Player
self.physicsBody?.categoryBitMask = PhysicsCategory.Ground
self.physicsBody?.collisionBitMask = PhysicsCategory.All
self.physicsBody?.affectedByGravity = false
self.physicsBody?.allowsRotation = false
self.physicsBody?.isDynamic = false
self.physicsBody?.mass = 1.99999
self.zPosition = -20
self.name = "Ground";
}
required init?(coder aDecoder: NSCoder) {
// Decoding length here would be nice...
super.init(coder: aDecoder)
}
}
You might not need to override the original init() method but I didn't test anything.