我在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.gameSpeed
变量的新值。
所以,我的问题很简单:如何提高背景图像的速度(缩短持续时间)&#39;根据{{1}}变量的移动?
谢谢!
答案 0 :(得分:2)
您可以使用gameSpeed
变量来设置背景的速度。为了实现这一点,首先,你需要引用你的两个背景片段(如果你想要的话,还需要更多):
class GameScene: SKScene {
lazy var backgroundPieces: [SKSpriteNode] = [SKSpriteNode(imageNamed: "Background"),
SKSpriteNode(imageNamed: "Background")]
// ...
}
现在您需要gameSpeed
变量:
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
中正确定位每个部分。此外,为了使这种方法起作用,每个背景片需要一个物理体,这样你就可以很容易地改变它的速度。
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
}
}
}
答案 1 :(得分:0)
你可以使用这样的东西
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
}