SKSpriteNode子类化swift [英] SKSpriteNode subclassing swift
问题描述
我已经找到了一些帖子,但我仍然对如何做到这一点感到困惑。我知道我必须使用指定的初始化程序,它是init(纹理:SKTexture!,颜色:UIColor!,大小:CGSize)。真的,我还是不会用它。我想只为sprite节点添加一些属性。
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.
推荐答案
只需将便利初始化程序
更改为:
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
}
在Swift中,便利初始化程序
必须:
In Swift, a convenience initializer
must:
- 调用同一类的另一个便利初始值设定项或类的指定初始值设定项(不是超类)
- 仅在致电
self.init [...]
- 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[...]
请参阅有关初始化程序的Swift文档以获取帮助: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097- CH18-XID_323
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
希望这有帮助,
这篇关于SKSpriteNode子类化swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!