【问题标题】:SpriteKit background image scrolling flickers at seam lineSpriteKit 背景图像滚动在接缝处闪烁
【发布时间】:2020-01-11 22:55:39
【问题描述】:

我正在使用 SpriteKit 创建一个 2D macOS 游戏,我想要一个从左到右连续滚动的背景。

我有一个与我的框架大小相同的背景图像。图像是并排复制的:最初左边是居中的,右边是屏幕外的。两张图片 (SKSpriteNode) 都经过动画处理,可以在屏幕上滑动,然后在移动完整帧宽度后重置它们的位置。

以下是相关代码:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    private var background = SKSpriteNode()

    func makeBackground() {
        let texture = SKTexture(imageNamed: "bg-empty")
        let scroll = SKAction.move(by: CGVector(dx: -texture.size().width, dy: 0), duration: 30)
        let reset = SKAction.move(by: CGVector(dx: texture.size().width, dy: 0), duration: 0)
        let animation = SKAction.repeatForever(SKAction.sequence([scroll, reset]))

        for idx in 0...1 {
            background = SKSpriteNode(texture: texture)
            background.position = CGPoint(x: CGFloat(idx)*texture.size().width, y: self.frame.midY)
            background.zPosition = -1
            background.run(animation)
            self.addChild(background)
        }
    }

    override func didMove(to view: SKView) {        
        makeBackground()
    }    
}

虽然这可行,但我注意到在连接的接缝处出现了特别的黑色(约 1 像素垂直条)闪烁。

是什么导致了这种闪烁,我该如何消除它?

【问题讨论】:

    标签: swift macos sprite-kit


    【解决方案1】:

    您遇到浮点舍入错误。这将导致您的第一个 BG 向下舍入,而您的第二个 BG 向上舍入,给您 1 个像素的间隙。

    请尝试以下代码

    class GameScene: SKScene {
    
        private var background = SKNode()
    
        func makeBackground() {
            let texture = SKTexture(imageNamed: "bg-empty")
            let scroll = SKAction.move(by: CGVector(dx: -texture.size().width, dy: 0), duration: 30)
            let reset = SKAction.move(by: CGVector(dx: texture.size().width, dy: 0), duration: 0)
            let animation = SKAction.repeatForever(SKAction.sequence([scroll, reset]))
    
            for idx in 0...1 {
                let subNode = SKSpriteNode(texture: texture)
                subNode.position = CGPoint(x: CGFloat(idx)*texture.size().width, y: self.frame.midY)
    
                background.addChild(subNode)
            }
            background.zPosition = -1
            background.run(animation)
            self.addChild(background)
        }
    
        override func didMove(to view: SKView) {        
            makeBackground()
        }    
    }
    

    现在您可以避免差距,因为您没有运行 2 个不同的操作。

    如果您希望能够双向滚动。然后在背景左侧放置一个纹理。

    这会在你的主背景前后放置一个背景节点,基本上把它变成一个大节点,只有中间的纹理完整显示。

    如果您有多个背景图像,则只需将背景的最后一帧也放在左侧

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多