我在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变量的新值.
所以,我的问题很简单:如何根据self.gameSpeed变量提高背景图像移动的速度(缩短持续时间)?
谢谢!
最佳答案 您可以使用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
}
您可以在update中更新gameSpeed,例如gameSpeed = 0.5.
最后,在更新中,您需要检查背景片是否已经离屏(左侧).如果有,则需要将其移动到背景片段的末尾:
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
}
}
}