SpriteKit “START” button that calls start() in the scene its in

拟墨画扇 提交于 2019-12-14 02:13:41

问题


How do I compose a touchesBegun command in a StartButton class that calls start() in the scene any instance of itself has been placed in?

I know... probably OOP 101. But well beyond me, today.

UPDATE:

Here is how I currently (partially) solve the problem. It doesn't feel right, but it works, somewhat. Not as much as I'd like:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    SoundManager.playSceneStartSound()
    run(ready)
     if CEO.startButtonIsActive{
        print("We're STARTING NOW...")
        if let menuScene = self.scene as? Menu_Memory {
            menuScene.startTheGame()
            }
        else
        if let menuScene = self.scene as? Menu_Chaser {
            menuScene.startTheGame()
            }
        else
        if let menuScene = self.scene as? Menu_Picker {
            menuScene.startTheGame()
            }
        else
        if let menuScene = self.scene as? Menu_Q_AndA {
            menuScene.startTheGame()
            }
        else
        {print("Houston, we have a problem... no gameScene")}
        }
    else
    {
    print("You still have some preparation to do, amigo!")
    }
}

Alternatively, the ability to pass a Class Type would be helpful too. This is almost a separate question, but for the fact I think they're very closely related, perhaps.

At any rate: in a button, trying to create a reference to a class type, I've tried a bunch of variations, with no luck.

Some of my ridiculous attempts, all fail:

Menu_Memory is a SKScene

    var menuClass01: Menu_Memory.self
    var menuClass02: AnyClass = Menu_Memory.self
    var menuClass03: AnyClass = Menu_Memory(self)
    var menuClass04: AnyClass as! Menu_Memory.self
    var menuClass05: AnyClass as! Menu_Memory(self)

回答1:


UPDATE Now that I have a clue as to what ur doing. Should be self-explaining. Yell at me if it isn't:

public extension SKScene {
  func startGame() { // Because startTheGame is a terriblename..
    // Override in your subclasses of SKScene if desired.
  }
}

enum Menu { // Used as namespace for chaser and menu classes

  final class Chaser: SKScene {
    override func startGame() {
      print("chaser started")
    }
  }

  final class Memory: SKScene {
      override func startGame() {
      print("memory started")
    }
  }
}

.

final class Button: SKNode {
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    scene!.startGame() // No need for guard / if-let,
                       // because how can you click the node if its scene is nil :)?
  }
}


来源:https://stackoverflow.com/questions/41092440/spritekit-start-button-that-calls-start-in-the-scene-its-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!