带有SpriteKit的无限背景问题

问题描述 投票:0回答:2

我一直在尝试实现无限的背景动画,该动画应在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的偏移量。我在做什么错?

编辑:原来错误位于我的图像中,该图像显示一些空白行,因此生成了可视化故障。所以我的代码可以正常工作。

swift background sprite-kit frame updates
2个回答
1
投票

我进行测试,很可能您应该使用类似的东西:

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随时查看和使用。

enter image description here


1
投票

您的问题是浮点数学运算,导致舍入错误。我现在正在打电话,所以我无法编写代码,但是您要做的是有1个父级SKNode来处理整个背景。

将背景条添加到父节点。然后,您仅将移动动作放在父项上。

当每个条子离开屏幕时,您将条子移到其他条子的末尾。

此跳转应始终使用整数数学完成,不留任何漏洞。

基本上:浮点移动数学运算在父节点上完成。

基于整数的瓦片跳跃在每个条子上完成。

© www.soinside.com 2019 - 2024. All rights reserved.