Initialize a Custom SKSpriteNode with its properties from the editor
我制作了一个名为SKGlowNode的简单自定义类,作为SKSpriteNode的子类。我最初希望能够创建一个自定义类,并像使用SKSpriteNode一样在编辑器中输入所有init参数。但是,我发现这还不可能,因此我不得不尝试对用户数据进行处理。我在编辑器中这样设置节点:
简单地像这样自定义类:
这是我的SKGlowNode课程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import Foundation import SpriteKit class SKGlowNode: SKSpriteNode{ let colors = [UIColor.blue,UIColor.green,UIColor.red,UIColor.orange,UIColor.purple,UIColor.yellow,UIColor.white,UIColor.magenta] required init?(coder aDecoder: NSCoder) { super.init(texture: texture, color: .black, size: size)//error here let glowIndex = self.userData?.value(forKey:"glowColorIndex") as? Int ?? 0 let glowTexture = self.userData?.value(forKey:"glowTexture") as? String ??"squareBg" addGlow(radius: 75, texture: SKTexture(imageNamed: glowTexture), color: colors[glowIndex]) //This glow function works and is an extension from a SKSpriteNode where it creates a glow from a texture with certain color } } |
很显然,在指定的行上出现错误,因为我无法使用这些变量初始化超类,但是我不知道要放置什么以使其使用编辑器中已定义的值进行初始化,因为如果没有自定义类。谢谢
您需要为您的类init提供适当的Super.init。
如果要在init()中实例化子类SKSpriteNode,无论它是默认的还是具有自定义参数的自定义init,请使用
1 | super.init(texture: SKTexture, color: SKColor, size: CGSize) |
如果要从sks场景文件中实例化它,则需要调用init?(编码器aDecoder:NSCoder),并且需要具有
1 2 3 | required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } |