使用精灵工具包垂直滚动背景的问题

时间:2015-05-07 08:29:57

标签: swift sprite-kit skspritenode

我正在尝试垂直滚动游戏背景,它可以工作一段时间,后来背景变空。这就是我的尝试:

var background = SKSpriteNode(imageNamed: "bgPlayScene")

func addBG() {

    let backgroundTexture = SKTexture(imageNamed: "bgPlayScene")

    let shiftBackground = SKAction.moveToY(-backgroundTexture.size().height, duration: 9)
    let replaceBackground = SKAction.moveToY(backgroundTexture.size().height, duration: 0)
    let movingAndReplacingBackground = SKAction.repeatActionForever(SKAction.sequence([shiftBackground,replaceBackground]))

    for var i = 0; i<3; i++ {
        println(i)
        //defining background; giving it height and moving width
        background=SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.size.width = self.frame.width
        background.runAction(movingAndReplacingBackground)

        self.addChild(background)
    }
}

这就是我得到的:http://gyazo.com/3da3a267aeb030225fdb8c0d563276aa 我不知道自己错过了什么。如果还有其他更好的办法,请告诉我。

1 个答案:

答案 0 :(得分:4)

根据iAnum的建议,我从post得到答案,这是我的代码:

这样我添加了2个背景。

func addScrollingBG() {

    bg1 = SKSpriteNode(imageNamed: "bgPlayScene")
    bg1.anchorPoint = CGPointZero
    bg1.position = CGPointMake(0, 0)
    bg1.size = CGSize(width: frame.size.width, height: frame.size.height)
    addChild(bg1)

    bg2 = SKSpriteNode(imageNamed: "bgPlayScene")
    bg2.anchorPoint = CGPointZero
    bg2.position = CGPointMake(0, bg1.size.height + 1)
    bg2.size = CGSize(width: frame.size.width, height: frame.size.height)
    self.addChild(bg2)

}

这是我的更新方法:

override func update(currentTime: NSTimeInterval) {

    bg1.position = CGPointMake(bg1.position.x, bg1.position.y-4)
    bg2.position = CGPointMake(bg2.position.x, bg2.position.y-4)

    if bg1.position.y < -bg1.size.height {
        bg1.position = CGPointMake(bg1.position.x, bg2.position.y + bg2.size.height)
    }
    if bg2.position.y < -bg2.size.height {
        bg2.position = CGPointMake(bg2.position.x, bg1.position.y + bg1.size.height)
    }
}