ios - 在swift中点击一个颜色 Sprite 后如何返回到之前的场景?

标签 ios swift button sprite-kit scene

因此,对于一个学校项目,我的任务是制作一款 2D 游戏。游戏很好,但我正在为如何制作后退按钮(在页面中间)而苦苦挣扎,所以想知道是否有特定的代码可以使它正常工作。我正在使用 spriteKit,所以我试图在点击一个彩色 Sprite 后返回到之前的场景。

如果这是一个愚蠢的问题,我深表歉意,但我对 Swift 有点陌生。

亲切的问候, 詹姆斯

最佳答案

这是一个示例,说明如何使用彩色 sprite 创建按钮。它展示了如何设置按钮来接收触摸事件,以及如何使用这些触摸事件在场景之间导航。

在此示例中,您可以向前导航到新场景并向后导航到以前的场景。

import SpriteKit

class Button: SKSpriteNode {

    var tapped: (() -> Void)?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        tapped?()
    }

}

class GameScene: SKScene {

    var parentScene: SKScene?
    var sceneCount = 1

    override func didMove(to view: SKView) {
        if parentScene != nil {
            let backButton = addButton(color: .red, position: CGPoint(x: -200, y: 0))
            backButton.tapped = {
                if let previousScene = self.parentScene {
                    view.presentScene(previousScene)
                }
            }
        }

        let nextButton = addButton(color: .blue, position: CGPoint(x: 200, y: 0))
        nextButton.tapped = {
            if let nextScene = SKScene(fileNamed: "GameScene") as? GameScene {
                nextScene.scaleMode = self.scaleMode
                nextScene.parentScene = self
                nextScene.sceneCount = self.sceneCount + 1
                view.presentScene(nextScene)
            }
        }

        let label = SKLabelNode(text: "Scene \(sceneCount)")
        addChild(label)
    }

    func addButton(color: SKColor = .white, position: CGPoint = .zero) -> Button {
        let button = Button(color: color, size: CGSize(width: 200, height: 200))
        button.position = position
        button.isUserInteractionEnabled = true
        addChild(button)
        return button
    }

}

关于ios - 在swift中点击一个颜色 Sprite 后如何返回到之前的场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44079350/

相关文章:

ios - 在应用程序第一次运行时显示隐藏的主视图 Controller

ios - 如何在 Swift 中的函数外部使用变量声明?

ios - 更新 uitableview 标题上的文本

iOS 开发 - 圆形矩形按钮向下移动子菜单

ios - Swift 如何获取 UIAlertController 标题高度

iphone - 如何知道 AVPlayer 何时使用纯音频比特率?

ios - CAShapeLayer 和 SpriteKit

android - 即使MediaPlayer已经在播放声音,如何在单击按钮时播放声音?

button - 在 SilverStripe 中向 CMS 添加按钮

ios - 使用 Core Data 时如何 NSPredicate 建立一对一关系?