Alan Scarpa
Alan Scarpa

Reputation: 3570

Scrolling Background creating a gap between images - Swift

I've created an infinite scrolling background out of 2 images. As the scrolling speed increases, a gap begins to appear between the images. Here is my code:

 override func update(currentTime: CFTimeInterval) {

    var fallingSpeed = 4 + speedIncrease

    background.position.y = background.position.y - fallingSpeed
    background2.position.y = background2.position.y - fallingSpeed

    if background.position.y <= 0 {
        background.position.y = size.height*2 - (fallingSpeed)

    }
    if background2.position.y <= 0 {
        background2.position.y = size.height*2 - (fallingSpeed)

    }
}

speedIncrease increases by +.1 every time the user taps the screen because I want the background to move faster as the game goes on. Both backgrounds are the same image and size.

The gap only occurs as speedIncrease increases. speedIncrease is initially set to 0 and the background scrolls smoothly with no gap. When I start tapping the screen and increasing speedIncrease, then the gap appears.

Any suggestion as to how I can remove the gap? I'm still very new to Swift and Obj-C so any advice for a beginner would be very appreciated.

Upvotes: 1

Views: 637

Answers (1)

dknldesign
dknldesign

Reputation: 11

I have had a similar issue, and managed to fix it by setting my position to a CGPoint with whole pixel (Integer) values. My assumption is that your problem is similar, and is caused because your background is drawn at fractions of a pixel.

Since you are only changing the position.y, you need a CGFloat, so you could simply round the number: background.position.y = round(some_CGFloat) For Retina (@2x) screens, the pixels are actually on each 0.5 of the position.y. In this case you could do this: background.position.y = round(some_CGFloat * 2.0) / 2.0

Try the following code (assuming Retina display):

override func update(currentTime: CFTimeInterval) {

  var fallingSpeed = 4 + speedIncrease

  background.position.y = round((background.position.y - fallingSpeed) * 2.0) / 2.0
  background2.position.y = round((background2.position.y - fallingSpeed) * 2.0) / 2.0

  if background.position.y <= 0 {
    background.position.y = round((size.height * 2 - fallingSpeed) * 2.0) / 2.0
  }
  if background2.position.y <= 0 {
    background2.position.y = round((size.height * 2 - fallingSpeed) * 2.0) / 2.0
  }
}

I do realize this is an older question, but I hope it can help people with similar issues.

Upvotes: 1

Related Questions