在SpriteKit中逐渐增加滚动背景的速度

我在SpriteKit中做了一个简单的游戏,我有一个滚动的背景。 简单地发生的是当游戏场景被加载时,一些背景图像彼此相邻放置,然后当图像滚动出屏幕时水平移动图像。 这里是我的游戏场景的didMoveToView方法的代码。

 // self.gameSpeed is 1.0 and gradually increases during the game let backgroundTexture = SKTexture(imageNamed: "Background") var moveBackground = SKAction.moveByX(-self.frame.size.width, y: 0, duration: (20 / self.gameSpeed)) var replaceBackground = SKAction.moveByX(self.frame.size.width, y: 0, duration: 0) var moveBackgroundForever = SKAction.repeatActionForever(SKAction.sequence([moveBackground, replaceBackground])) for var i:CGFloat = 0; i < 2; i++ { var background = SKSpriteNode(texture: backgroundTexture) background.position = CGPoint(x: self.frame.size.width / 2 + self.frame.size.width * i, y: CGRectGetMidY(self.frame)) background.size = self.frame.size background.zPosition = -100 background.runAction(moveBackgroundForever) self.addChild(background) } 

现在我想增加游戏某些点滚动背景的速度。 您可以看到背景的水平滚动的持续时间设置为(20 / self.gameSpeed) 。 显然这是行不通的,因为这个代码只运行一次,因此移动速度永远不会更新以解释self.gameSpeedvariables的新值。

所以,我的问题很简单:如何根据self.gameSpeedvariables提高背景图像运动的速度(减less持续时间)?

谢谢!

你可以使用gameSpeedvariables来设置背景的速度。 为了这个工作,首先,你需要参考你的两个背景(或更多,如果你想):

 class GameScene: SKScene { lazy var backgroundPieces: [SKSpriteNode] = [SKSpriteNode(imageNamed: "Background"), SKSpriteNode(imageNamed: "Background")] // ... } 

现在你需要你的gameSpeedvariables:

 var gameSpeed: CGFloat = 0.0 { // Using a property observer means you can easily update the speed of the // background just by setting gameSpeed. didSet { for background in backgroundPieces { // Minus, because the background is moving from left to right. background.physicsBody!.velocity.dx = -gameSpeed } } } 

然后在didMoveToView正确地didMoveToView每件作品。 而且,为了使这个方法能够工作,每个背景都需要一个物理体,所以你可以很容易地改变它的速度。

 override func didMoveToView(view: SKView) { for (index, background) in enumerate(backgroundPieces) { // Setup the position, zPosition, size, etc... background.physicsBody = SKPhysicsBody(rectangleOfSize: background.size) background.physicsBody!.affectedByGravity = false background.physicsBody!.linearDamping = 0 background.physicsBody!.friction = 0 self.addChild(background) } // If you wanted to give the background and initial speed, // here's the place to do it. gameSpeed = 1.0 } 

你可以更新gameSpeed update ,例如gameSpeed += 0.5

最后,在update您需要检查背景是否已经离屏(左侧)。 如果有它需要被移动到背景碎片链的末尾:

 override func update(currentTime: CFTimeInterval) { for background in backgroundPieces { if background.frame.maxX <= 0 { let maxX = maxElement(backgroundPieces.map { $0.frame.maxX }) // I'm assuming the anchor of the background is (0.5, 0.5) background.position.x = maxX + background.size.width / 2 } } } 

你可以利用这样的东西

 SKAction.waitforDuration(a certain amount of period to check for the updated values) SKAction.repeatActionForever(the action above) runAction(your action) { // this is the completion block, do whatever you want here, check the values and adjust them accordly }