连续滚动背景

时间:2018-05-29 15:25:55

标签: swift sprite-kit

我试图制作一个马里奥'像背景是一个图像但连续滚动并移动位置以给它一个滚动效果的游戏。目前,背景图像显示灰色背景,然后再显示背景图像。

enter image description here

有人可以帮忙看看我哪里出错了。

class GameScene: SKScene {
 
    let background = SKSpriteNode(texture:SKTexture(imageNamed: "background"))
 
    var lastFrameTime : TimeInterval = 0

    var deltaTime : TimeInterval = 0
 
    override func didMove(to view: SKView) {
        background.position = CGPoint(x: 0, y: 0)
    self.background.setScale(0.75)
    self.addChild(background)
    }
 
    override func update(_ currentTime: TimeInterval) {
        if lastFrameTime <= 0 {
            lastFrameTime = currentTime
        }
 
        deltaTime = currentTime - lastFrameTime
        lastFrameTime = currentTime
 
        self.moveSprite(sprite: background, nextSprite: background, speed:10)
    }
 
    func moveSprite(sprite : SKSpriteNode,
                    nextSprite : SKSpriteNode, speed : Float) -> Void {
        var newPosition = CGPoint.zero
 
        for spriteToMove in [sprite, nextSprite] {
 
            newPosition = spriteToMove.position
            newPosition.x -= CGFloat(speed * Float(deltaTime))
            spriteToMove.position = newPosition
 
            if spriteToMove.frame.maxX < self.frame.minX {
 
                spriteToMove.position = CGPoint(x: spriteToMove.position.x + spriteToMove.size.width * 2, y: spriteToMove.position.y)
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您需要添加其他背景图像并将其设置在原始背景图像旁边。在那之后,当背景离开屏幕时,你基本上玩一个跳蛙游戏。看看我发布的课程,了解滚动背景应该如何工作。

class GameScene: SKScene {

    let background = SKSpriteNode(texture:SKTexture(imageNamed: "background"))
    let background2 = SKSpriteNode(texture:SKTexture(imageNamed: "background"))

    var lastFrameTime : TimeInterval = 0

    var deltaTime : TimeInterval = 0

    override func didMove(to view: SKView) {
        background.position = CGPoint(x: 0, y: 0)
        background2.position = CGPoint(x: background.size.width, y: 0)
//    self.background.setScale(0.75)
        self.addChild(background)
        self.addChild(background2)
    }

    override func update(_ currentTime: TimeInterval) {
        if lastFrameTime <= 0 {
            lastFrameTime = currentTime
        }

        deltaTime = currentTime - lastFrameTime
        lastFrameTime = currentTime

        self.moveBackground(background,speed:10)
        self.moveBackground(background2,speed:10)
    }

    func moveBackground(_background:SKSprite,speed : Float) -> Void {
      background.position.x -= CGFloat(speed * Float(deltaTime))
      if background.position.x < -background.size.width{
          background.position.x += background.size.width * 2
      }
    }