如何从 SKscene 检测设备旋转

how to detect device rotation from SKscene

我只是在试用 XCode 的 SpriteKit 示例应用程序,我正在对其进行更改以测试和学习。

我想在 GameScene(SKScene 子类)中找到一个检测设备旋转的函数,即当设备从纵向旋转到横向等时应触发此函数。

我找到了一个函数

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation)

但是这个函数只在GameViewController(UIViewController子类)中有效。我需要 SKScene 子类中存在的类似功能。

非常感谢。

didRotate(from:) is deprecated since iOS 8.0 so we are going to use the new method.

你需要告诉你的游戏ViewController每次发生旋转时通知当前场景。

1。 CanReceiveTransitionEvents 协议

让我们定义一个协议来表示符合类型(我们的场景)可以接收旋转事件

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
}

2。使我们的场景符合 CanReceiveRotationEvents

现在让我们自己的 SKScene 符合协议

class GameScene: SKScene, CanReceiveTransitionEvents {

    func viewWillTransition(to size: CGSize) {
        // this method will be called when a change in screen size occurs
        // so add here your code
    }
}

If you have multiple scenes just repeat for each one.

3。 ViewController 应该在每次旋转时通知场景

最后让控制器在每次检测到旋转时调用相关的场景方法

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

    super.viewWillTransition(to: size, with: coordinator)

    guard
        let skView = self.view as? SKView,
        let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

    canReceiveRotationEvents.viewWillTransition(to: size)
}

就是这样。