代码之家  ›  专栏  ›  技术社区  ›  Matthew the Coder

如何从SKscene检测设备旋转

  •  1
  • Matthew the Coder  · 技术社区  · 8 年前

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

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

    我找到了一个函数

    override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation)

    但此函数仅在GameViewController(UIViewController子类)中起作用。我需要一个类似的函数,存在于SKScene子类中。

    非常感谢。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Luca Angeletti    8 年前

    didRotate(from:) 自iOS 8.0以来已弃用,因此我们将使用新方法。

    每次旋转发生时,您需要告诉GameViewController通知当前场景。

    1、CanReceiveTransitionEvents协议

    让我们定义一个协议,说明conform类型(我们的场景)可以接收旋转事件

    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
        }
    }
    

    如果有多个场景,只需对每个场景重复。

    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)
    }
    

    就是这样。

    推荐文章