简体   繁体   中英

Repeating the background when touches began in Spritkit

I have a simple code that repeats the background for ever using Spritekit, i want the background to be still before any touches occur and only start animating or scrolling when any touches began

    *// animate the background*

    let background = SKTexture(imageNamed: "bg.png")

    let moveTheBackground = SKAction.move(by: CGVector(dx: -
    background.size().width, dy:0),  duration: 10)

    let backgroundToOriginalPosition = SKAction.move(by: CGVector(dx: 
    background.size().width, dy: 0), duration: 0)

    let animateTheBackground = 
    SKAction.repeatForever(SKAction.sequence([moveTheBackground, 
    backgroundToOriginalPosition]))


    *// loop the background animation*

    var i:CGFloat = 0
    while i < 2 {

        bg = SKSpriteNode(texture: background)
        bg.position = CGPoint(x: background.size().width * i, y: self.frame.midY)
        bg.size.height = self.frame.height
        bg.zPosition = -1
        bg.run(animateTheBackground)
        self.addChild(bg)

        i += 1
    }

i want this code to happen when touchesbegan in SpriteKit, any help would be greatly appreciated

In any game programming, ideal way to show horizontal scrolling is use 2 background image and add one after one in horizontal. Move both and whenever background1 cross leftmost 0(in right to left scroll) change its position to width as x. Use main game loop to increment both backgrounds position. In your case use one flag named allowScroll, set this true when touchesBegin. If allowScroll set true then increment/decrement background image positions in game loop.

将代码移动到touchesMoved内部,以使背景相应地移动到触摸

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM