ios - 滚动背景在图像之间创建间隙 - Swift

标签 ios xcode swift

我用 2 张图片创建了一个无限滚动的背景。随着滚动速度的增加,图像之间开始出现间隙。这是我的代码:

 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 都会增加 +.1,因为我希望背景随着游戏的进行而移动得更快。 两个背景的图像和大小相同。

只有当 speedIncrease 增加时才会出现差距。 speedIncrease 最初设置为 0,背景平滑滚动,没有间隙。当我开始点击屏幕并增加 speedIncrease 时,就会出现间隙。

关于如何消除差距有什么建议吗?我对 Swift 和 Obj-C 还是很陌生,所以非常感谢对初学者的任何建议。

最佳答案

我遇到过类似的问题,并设法通过将我的位置设置为具有完整像素(整数)值的 CGPoint 来解决它。我的假设是你的问题是相似的,并且是因为你的背景是以像素的分数绘制的。

因为你只是改变 position.y,你需要一个 CGFloat,所以你可以简单地四舍五入这个数字:background.position.y = round(some_CGFloat) 对于 Retina (@2x) 屏幕,像素实际上位于 position.y 的每 0.5 个位置。在这种情况下,您可以这样做:background.position.y = round(some_CGFloat * 2.0)/2.0

尝试以下代码(假设 Retina 显示屏):

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
  }
}

我确实意识到这是一个较老的问题,但我希望它可以帮助有类似问题的人。

关于ios - 滚动背景在图像之间创建间隙 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26392519/

相关文章:

ios - 在 UIView 子类中实现 UIResponder 触摸方法是否违反了 MVC?

ios - 多目标 iOS 应用程序权利中的钥匙串(keychain)访问组

ios - 使用 NSURLRequest 的 AFNetworking 3.0 AFHTTPSessionManager

ios - itunes connect,上传后应用程序大小没有意义

swift - 案例(让名字,让x)

ios - 如何将MKCircleView从一个位置移动到MKMapView中的另一个位置?

xcode - SwiftUI:如何在预览中显示测试 CoreData 实例?

ios - IBInspectable 不适用于 Int 或 UInt

swift - 3d模型SceneKit/ARKit最好使用哪种格式文件

ios - Swift 4.2 升级后将 Swift 类桥接到 React Native