首页 > 解决方案 > 分裂SpriteKit的无限背景问题

问题描述

我一直在尝试实现一个无限的背景动画,它应该在 4 个相等高度的图像之间变化,然后重复这个序列。但是,它似乎无法正常工作。

笔记anchorPoint = CGPoint(x: 0.5, y: 0)

func updateBackground(currentTime: TimeInterval){
        var delta: CGFloat = 0.0
        if lastUpdate != nil {
            delta = CGFloat(currentTime - lastUpdate)
        }

        //First increment position
        activeBackground1.position.y += delta*backgroundVelocity
        activeBackground2.position.y += delta*backgroundVelocity

        //Detect bounds surpass
        if activeBackground1.position.y > activeBackground1.size.height + screen.height/2 {
            lastSky = (lastSky + 1)%4
            sky1 = SKTexture(imageNamed: "sky" + String(lastSky))
            activeBackground1.texture = sky1
            //Reposition: background1 new position is equal to minus the entire height of
            //background2 + its y size.
            activeBackground1.position.y = -abs(activeBackground2.size.height-activeBackground2.position.y)
        }

        if activeBackground2.position.y > activeBackground2.size.height + screen.height/2 {
            lastSky = (lastSky + 1)%4
            sky1 = SKTexture(imageNamed: "sky" + String(lastSky))
            activeBackground2.texture = sky1
            activeBackground2.position.y = -abs(activeBackground1.size.height-activeBackground1.position.y)
        }
    }

更新算法工作正常,但是当需要重新定位两个背景中的一个时,似乎10.0 CGFloat从一个背景到另一个背景的偏移量约为。我究竟做错了什么?

编辑:原来错误位于我的图像中,它显示了一些空白行,因此产生了可视化故障。所以我的代码完美运行。

标签: swiftbackgroundsprite-kitframeupdates

解决方案


我做测试,很可能你应该使用类似的东西:

activeBackground2.position.y = activeBackground1.size.height + activeBackground1.position.y

代替

activeBackground2.position.y = -abs(activeBackground1.size.height-activeBackground1.position.y)

我做了这个例子,它工作正常:https ://github.com/Maetschl/SpriteKitExamples/tree/master/InfiniteBackground/InfiniteBackground 随意查看和使用。

在此处输入图像描述


推荐阅读