gpt4 book ai didi

ios - 如何从 SKscene 检测设备旋转

转载 作者:行者123 更新时间:2023-11-29 11:35:07 25 4
gpt4 key购买 nike

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

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

我找到了一个函数

override func didRotate(fromInterfaceOrientation: UIInterfaceOrientation)

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

非常感谢。

最佳答案

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

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

1。 CanReceiveTransitionEvents 协议(protocol)

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

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

2。使我们的场景符合 CanReceiveRotationEvents

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

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 应该在每次旋转时通知场景

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

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

就是这样。

关于ios - 如何从 SKscene 检测设备旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com