【问题标题】:How can I create a finite, scrollable background in SpriteKit?如何在 SpriteKit 中创建有限的、可滚动的背景?
【发布时间】:2018-02-26 13:14:02
【问题描述】:

我希望在 Sprite Kit 中有一个可滚动的背景。我尝试了一些在线提供的other 解决方案,但它们实现了无限滚动背景,我无法根据我的需要调整代码。

这里有一些示例代码,我必须尝试让背景移动(没有检测到到达背景的尽头) - 但它非常不稳定而且一点也不平滑。

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchLocation = touches.first?.location(in: self), let node = nodes(at: touchLocation).first {
        if node.name != nil {
            if node.name == "background" {
                background.position = touchLocation
            }
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchLocation = touches.first?.location(in: self), let node = nodes(at: touchLocation).first {
        if node.name != nil {
            if node.name == "background" {
                background.position = touchLocation
            }
        }
    }
}

下图展示了我想要实现的目标 - 我希望代码能够检测到您何时到达背景的尽头,并阻止您进一步移动它。

【问题讨论】:

  • 创建一个有限宽度的 UIScrollView。它会限制你进一步滚动。
  • 创建一个实际的有限场景怎么样?
  • 不要创建 UIScrollView,你在 SpriteKit 中工作,而不是 UIKit。你所需要的只是界限,if bgposition. x &lt; minimumbackground then bgposition.x = minimumbackground

标签: ios swift sprite-kit


【解决方案1】:

因此,考虑到需要为背景设置最大和最小 X 坐标值的 @KnightOfDragon's 评论,我能够解决我自己的问题。我的代码中已经有向左/向右滑动识别器(用于我的游戏中的另一个目的),并且我能够重用这些来满足我的需求。代码如下:

在didMove():

swipeRightRec.addTarget(self, action: #selector(self.swipedRight) )
swipeRightRec.direction = .right
self.view!.addGestureRecognizer(swipeRightRec)

swipeLeftRec.addTarget(self, action: #selector(self.swipedLeft) )
swipeLeftRec.direction = .left
self.view!.addGestureRecognizer(swipeLeftRec)

然后是这些函数:

@objc func swipedRight() {
    if background.position.x + 250 > maxBackgroundX {
        let moveAction = SKAction.moveTo(x: maxBackgroundX, duration: 0.3)
        background.run(moveAction)
    } else {
        let moveAction = SKAction.moveTo(x: background.position.x + 250, duration: 0.3)
        background.run(moveAction)
    }
}

@objc func swipedLeft() {
    if background.position.x - 250 < minBackgroundX {
        let moveAction = SKAction.moveTo(x: minBackgroundX, duration: 0.3)
        background.run(moveAction)
    } else {
        let moveAction = SKAction.moveTo(x: background.position.x - 250, duration: 0.3)
        background.run(moveAction)
    }
}

是的,这意味着每次滑动时背景都会移动一定量,无论滑动有多大,但这正是我的游戏所需要的。我希望这可以帮助其他需要同样东西的人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 2022-12-24
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    相关资源
    最近更新 更多