2014-10-06 102 views
0

在xcode和spritekit中使用swift編程語言。我想讓我的背景圖像永久滾動。到目前爲止我有這個代碼,但是當我在模擬器中運行它時,它只經過一次並返回到灰色背景。我如何獲得它,使背景永遠重複。我已經有了移動它的背景,我想讓它永遠重複。在Swift中重複背景圖像

class GameScene: SKScene, SKPhysicsContactDelegate { 
var background = SKSpriteNode() 


     // Background 

    background = SKSpriteNode(imageNamed: "background") 
    background.position = CGPointMake(self.size.width/2, self.size.height/2) 
    addChild(background) 

    // Repeat Background Image Forever 

    moveForeverAction() 

    } 

     //loop background image infinitely 

    func moveForeverAction() { 
    let moveNode = SKAction.moveByX(0, y: background.size.height * 2.0 , duration: NSTimeInterval(0.01 * background.size.height * 2.0)) 
    let resetPosition = SKAction.moveByX(0, y: background.size.height * 2.0, duration: 0) 
    let moveNodeForever = SKAction.repeatActionForever(SKAction.sequence([moveNode, resetPosition])) 
    background.runAction(moveNodeForever) 
} 

回答

0

你必須runAction()3次。例如:

for var i:CGFloat = 0; i < 3; ++ I {

background.position = CGPointMake(background.size.width/2, i * background.size.height) 
background.runAction(moveNodeForever) 

}

+0

我把這段代碼放在我的項目中,並且出現錯誤。它說終止應用程序,由於未捕獲的異常「NSInvalidArgumentException」,原因:'試圖添加一個SKNode,它已經有一個父級:名稱:'(null)'texture:['background'(2480 x 3507)]] position :{1240,3507}大小:{2480,3507}旋轉:0.00' – user3886268 2014-10-07 16:36:40

+0

我把代碼放在didMoveToView中是否正確,因爲它不工作? – user3886268 2014-10-07 16:41:53

1

這是因爲你要添加相同的背景。 在循環中添加另一個免費聲明:

for var i:CGFloat=0; i < 3; ++i { 

**background = SKSpriteNode(imageNamed: "background")** 

background.position = CGPointMake(background.size.width/2, i * background.size.height) 
background.runAction(moveNodeForever) 

} 
+0

它的工作原理,但它不像我想要的那樣重複。當我第一次在模擬器中運行它時,我的背景圖像會從上到下一次,然後回到灰色背景。然後,它在一秒鐘後返回到我的背景圖像,並每3秒循環一次。它並沒有給人留下背景永遠在移動的印象。我如何才能做到這一點? – user3886268 2014-10-09 15:18:36

+0

感謝您的幫助! – user3886268 2014-10-09 15:19:23