在Swift中重复背景图像
在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)
}
你必须runAction()3次。例如:
for var i:CGFloat = 0; i < 3; ++ I {
background.position = CGPointMake(background.size.width/2, i * background.size.height)
background.runAction(moveNodeForever)
}
这是因为你要添加相同的背景。 在循环中添加另一个免费声明:
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)
}
它的工作原理,但它不像我想要的那样重复。当我第一次在模拟器中运行它时,我的背景图像会从上到下一次,然后回到灰色背景。然后,它在一秒钟后返回到我的背景图像,并每3秒循环一次。它并没有给人留下背景永远在移动的印象。我如何才能做到这一点? – user3886268 2014-10-09 15:18:36
感谢您的帮助! – user3886268 2014-10-09 15:19:23
我把这段代码放在我的项目中,并且出现错误。它说终止应用程序,由于未捕获的异常“NSInvalidArgumentException”,原因:'试图添加一个SKNode,它已经有一个父级:名称:'(null)'texture:['background'(2480 x 3507)]] position :{1240,3507}大小:{2480,3507}旋转:0.00' –
user3886268
2014-10-07 16:36:40
我把代码放在didMoveToView中是否正确,因为它不工作? – user3886268 2014-10-07 16:41:53