如何从视图控制器移动到 skscene [英] How to move from view controller to skscene
问题描述
我想以 swift 语言从 UIViewController
呈现 SKScene
,我正在 iOS 中开发游戏,菜单是 UIViewController
,游戏在 SpriteKit 中,我需要从菜单 (UIViewController
) 移动到游戏 (SKScene
) 按下按钮.我怎么能做这样的事情?
I want to present SKScene
from a UIViewController
in swift language,
I'm developing a game in iOS , the menu is a UIViewController
and the game is in SpriteKit, I need to move from the menu (UIViewController
) to the game (SKScene
) upon pressing a button.
How can I do something like that ?
推荐答案
就像@Ron Myschuk 所说的那样,您应该考虑将菜单移至 SpriteKit
.如果您想使用 UIKit
,您需要将 SKScene
与 UIViewController
通信(我想这是您的问题).
Like @Ron Myschuk said you should consider moving your menu to SpriteKit
. If you want to use UIKit
you will need to communicate the SKScene
with the UIViewController
(I guess that is your problem).
您可以通过 delegate 实现此目的模式.
使用此模式,您的代码可能如下所示:
Using this pattern your code might look something like this:
/// Game actions that should be notified.
Protocol GameSceneDelegate: class {
func gameDidEnd()
}
public class GameScene: SKScene {
weak var gameDelegate: GameSceneDelegate?
// MARK: - Menu Actions
func userDidPressMenuButton() {
///Do what you want to do..
}
}
class GameViewController: UIViewController, GameSceneDelegate{
var scene: GameScene?
override func viewDidLoad() {
if (self.view as! SKView?) != nil {
self.scene = GameScene(fileNamed: "GameScene")
}
self.scene?.gameDelegate = self
}
// MARK: - GameSceneDelegate methods
func gameDidEnd(){
///Do what you want to do..
}
// MARK: - Actions
@IBAction func pressMenuButtonAction(_ sender: Any) {
self.scene?.userDidPressMenuButton()
}
}
当您在 UIViewController
中按下按钮时,您会调用 SKScene
来执行它需要执行的操作.当场景需要告诉菜单一个相关的动作(比如游戏结束)时,它会调用它的委托,即你的 UIViewController
.
When a button is pressed in your UIViewController
you call the SKScene
to do what ever it needs to do. And when the scene needs to tell the menu a relevant action (like game finish) it calls its delegate, that is your UIViewController
.
这篇关于如何从视图控制器移动到 skscene的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!