我如何通过在 swift 操场上按下按钮来调用场景

How would I call a scene by pressing a button on swift playground

如何让这个按钮在点击时打开 GameScene1? 到目前为止,这是我的代码。

class GameScene1: SKScene{
    override func didMove(to view: SKView){
    }
}
let scene1 = GameScene1(size: CGSize(width: 400, height: 640))
scene1.scaleMode = .aspectFill
scene1.backgroundColor = .blue

let view2 = SKView(frame: CGRect(x:0, y:0, width: scene1.size.width, height: scene1.size.height
view2.presentScene(scene)
PlaygroundPage.current.liveView = view2



class Receiver{
    @objc func buttonClicked(){
    }
}
let view1 = UIView()
let receiver = Receiver()
let button = UIButton(frame: CGRect(x:10, y:10, width:100, height:50))
button.setTitle("start", for: .normal)
button.addTarget(receiver, action: #selector(Receiver.buttonClicked), for: .touchUpInside)
view.addSubview(button)

我不知道该怎么做。

好吧,我对 SKScene 的经验不多,但这就是我要做的。你真的只需要一个 SKView 在你的操场上,你可以将它作为 static let 存储在一个包含游戏变量的文件中。然后您可以创建不同的场景,例如菜单场景,第一层场景,第二层场景等。

以下代码创建一个按钮并为其指定一个操作。该动作创建一个名为场景的常量,这是您要移动到下一个场景的场景。然后你就用场景调用presentScene(),还有一个SKTransition,如下图,就是一个简单的2.5秒从右边滑动的动画

ButtonNode class,它只是一个充当按钮的节点,您可以将其添加到场景中。

class ButtonNode: SKSpriteNode {

    var action: ((ButtonNode) -> Void)?

    var isSelected: Bool = false {
        didSet {
            alpha = isSelected ? 0.8 : 1
        }
    }

    required init(coder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    init(texture: SKTexture, size: CGSize) {
        super.init(texture: texture, color: SKColor.white, size: size)
        isUserInteractionEnabled = true
    }

    override func touchesBegan(with event: NSEvent) {
        action?(self)
    }

    override func mouseDown(with event: NSEvent) {
        action?(self)
    }
}

创建按钮并赋予它移动到下一个场景的动作。这可以在任何 SKScene class.

中完成
startButton = ButtonNode(texture: SKTexture(imageNamed: "start-button"), size: CGSize(width: 184, height: 72))
        startButton.position = CGPoint(x: 0.0, y: 0.0)
        startButton.action = { (button) in
            if let scene = IntroCutScene(fileNamed: "IntroCutScene") {
                // Set the scale mode to scale to fit the window
                self.scene!.scaleMode = .aspectFill

                // Present the scene
                GameVariables.sceneView.presentScene(scene, transition: SKTransition.moveIn(with: SKTransitionDirection.right, duration: 2.5))
            }
        }
        self.addChild(startButton)