我一直在学习spritekit,但我在使用super.init时遇到了一些困难。我来自Java的背景,并想知道为什么我收到错误: " Super.Init在初始化程序中多次调用"
我想要实现的是一个构造函数,它为角色分配适当的静止纹理,同时还设置纹理数组,以便我可以调用它而不必担心传递它的值。
我已经查看了文档,但我认为我的咖啡水平已经耗尽,因为我真的无法理解为什么super.init可能会自称。您将提供的任何帮助将不胜感激。我确实搜索过类似的问题,却找不到一个问题,如果我错误地发布了这个答案的链接同样会受到赞赏。
class CharClass : SKSpriteNode
{
var textureAtlas = SKTextureAtlas()
var textureArray = [SKTexture]()
init() {
textureAtlas = SKTextureAtlas(named:"Org")
//likely should be a passed variable instead
for i in 1 ... textureAtlas.textureNames.count{
var Name = String();
if(i<10)
{
Name = "cWalk000\(i).png"
}
else
{
Name = "cWalk00\(i).png"
}
textureArray.append(SKTexture(imageNamed: Name));
let texture = SKTexture(imageNamed: textureAtlas.textureNames[0]);
super.init(texture:texture, color: UIColor.clear, size:texture.size())
self.size = CGSize(width:71 , height: 131);
self.position = CGPoint(x: -282.52, y:-141.5);
self.run(SKAction.repeatForever(SKAction.animate(with: textureArray, timePerFrame: accelSpeed)))
}
}
答案 0 :(得分:1)
rmaddy的回答是正确的。关闭for
循环,因为您只能拨打super.init
一次:
for i in 1 ... textureAtlas.textureNames.count {
let name: String
if(i < 10) {
name = "cWalk000\(i).png"
} else {
name = "cWalk00\(i).png"
}
textureArray.append(SKTexture(imageNamed: name))
}
let texture = SKTexture(imageNamed: textureAtlas.textureNames[0])
super.init( texture: texture,
color: UIColor.clear,
size: texture.size() )
另外,欢迎快速:)不要忘记;
是完全可选的/ thumbsup
此外,在尝试使用它之前不初始化某些内容是件好事。我知道Java强迫你这样做,但我将var name
更改为let name
,因为它实际上并不需要在那里进行初始化,也不需要进行变异。你实际上可以这样做:
i < 10 ? ( textureArray.append(SKTexture(imageNamed: "cwalk000\(i).png")) ) :
( textureArray.append(SKTexture(imageNamed: "cwalk00\(i).png" )) )
这通常可以加快您的代码速度,并为您节省8行原件;)只是一个新的更快捷的提示!