2015-11-08 55 views
2

我想开发一个游戏,需要使用SpriteKit和Swift在所有场景中具有共同背景。由于背景是常见的,它的行动必须是连续的,我创建的SKSpriteNode这样一个自定义的单子类:自定义SKSpriteNode addChild不工作

class BackgroundNode: SKSpriteNode { 
    static let sharedBackground = BackgroundNode() 

    private init() 
    { 
     let texture = SKTexture(imageNamed: "Background") 
     super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) 
     addActors() 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    private func addActors() { 
     addClouds() 
    } 

    private func addClouds() { 
     addCloud1() 
    } 

    private func addCloud1() { 
     let cloud1 = SKSpriteNode(imageNamed: "Cloud1") 
     cloud1.size = CGSizeMake(0.41953125*self.size.width, 0.225*self.size.height) 
     cloud1.position = CGPointMake(-self.size.width/2, 0.7*self.size.height) 
     self.addChild(cloud1) 
     let moveAction = SKAction.moveTo(CGPointMake(self.size.width/2, 0.7*self.size.height), duration: 20) 
     cloud1.runAction(SKAction.repeatActionForever(moveAction)) 
    } 
} 

而且从GameScene类我加入这个节点这样当前视图:

class GameScene: SKScene { 
    override func didMoveToView(view: SKView) { 
     BackgroundNode.sharedBackground.size = CGSizeMake(self.size.width, self.size.height) 
     BackgroundNode.sharedBackground.position = CGPointMake(self.size.width/2, self.size.height/2) 
     addChild(BackgroundNode.sharedBackground) 
    } 
} 

背景图像显示正确,但未添加云。截至上面的代码云应该出现在屏幕之外,然后再通过另一边缘进入屏幕,但为了验证它是否被添加,我甚至尝试将云添加到屏幕的中心,而没有任何动画。云仍没有出现。这里可能是什么问题?以及如何解决它?

编辑

我想通了,孩子却越来越增加,但获取添加,并通过一些远点屏幕上方移动。我还发现,它可能与云的锚点有关,但无论我设置哪个值作为锚点,云总是保留在屏幕的右上角。我可以做些什么关于锚点,使云显示,因为它应该(考虑左下角为(0,0)是我想要的)

回答

1

解决了这个问题。问题是我不得不手动设置场景和节点的锚点。将Scene和节点的定位点设置为(0,0)解决了问题。新代码如下:

GameScene

override func didMoveToView(view: SKView) { 
    anchorPoint = CGPointMake(0, 0) //Added this 
    BackgroundNode.sharedBackground.size = CGSizeMake(self.size.width, self.size.height) 
    BackgroundNode.sharedBackground.position = CGPointMake(0, 0) 
    addChild(BackgroundNode.sharedBackground) 
} 

BackgroundNode

private init() 
{ 
    let texture = SKTexture(imageNamed: "Background") 
    super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) 
    anchorPoint = CGPointMake(0, 0) //Added this 
    addActors() 
} 
+0

也许你应该标记您的答案解决了吗? – Stefan

+0

需要一点时间才能将自己的答案标记为已解决。 :-) –