Endless scrolling (repeating) background in Spritekit game - Swift

后端 未结 6 1846
野的像风
野的像风 2021-02-06 02:20

I want to Create a endless scrolling background for my spritekit game, iT should consist of one or two images probably, which repeat themselves? I found these one and two exampl

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 02:52

    Here what I came up with:

       func terrain() -> SKNode {
            let color = UIColor.init(red: randomColorChannel(), green: randomColorChannel(), blue: randomColorChannel(), alpha: 1.0)
    
            let scale: CGFloat = 1.0// UIScreen.mainScreen().scale
            let size = CGSizeMake(frame.size.width * scale, frame.size.height * scale)
            let node = SKSpriteNode.init(color: color, size: size)
            node.anchorPoint = CGPointZero
            node.position = CGPointMake(0, UIScreen.mainScreen().bounds.size.height)
    
            return node
        }
    

    And in update do this:

    override func update(currentTime: NSTimeInterval) {
            var newPosition1 = terrain1.position
            var newPosition2 = terrain2.position
    
            newPosition1.y -= terrainSpeed
            if newPosition1.y < 0 {
                newPosition2.y -= terrainSpeed
            }
    
            terrain1.position = newPosition1
            terrain2.position = newPosition2
    
            if terrain1.position.y <= -UIScreen.mainScreen().bounds.size.height {
                removeChildrenInArray([terrain1])
                terrain1 = terrain()
                addChild(terrain1)
            }
    
            if terrain2.position.y <= -UIScreen.mainScreen().bounds.size.height {
                removeChildrenInArray([terrain2])
                terrain2 = terrain()
                addChild(terrain2)
            }
        }
    

    So basically, terrain is placed above the view, and then they start moving down, and replaced by new ones when needed, to repeat.

提交回复
热议问题