首页 > 解决方案 > 旋转设备时如何更改 SKScene 大小?

问题描述

我试图制作一个使用递归函数呈现分形树的 SKScene。每个分支都是一个SKShapeNode. 初始线长度应始终是场景高度的百分比。我有一个用于当前返回的第一行长度的计算变量frame.height * 0.3。我的问题是我想在设备旋转时保持正确的百分比。我在 ViewController 中添加了以下代码:

    var scene: FractalTreeScene!
    override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
        if fromInterfaceOrientation == .landscapeLeft || fromInterfaceOrientation == .landscapeRight {
            scene.size = CGSize(width: 1337, height: 750)
        } else {
            scene.size = CGSize(width: 750, height: 1337)
        }
        scene.drawTree()
    }
    override func viewDidLoad() {
        super.viewDidLoad()


        if let view = self.view as! SKView? {
            // Load the SKScene from 'GameScene.sks'
            scene = FractalTreeScene()
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill
            if UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight {
                scene.size = CGSize(width: 1337, height: 750)
            } else {
                scene.size = CGSize(width: 750, height: 1337)
            }
            // Present the scene
            view.presentScene(scene)

            view.ignoresSiblingOrder = true

            view.showsFPS = true
            view.showsNodeCount = true
        }
    }

然后我以纵向启动应用程序,一切看起来都很好,然后我尝试旋转到横向并且大小根本没有改变(我添加了 print(size) 以更新场景中的功能)。然后我旋转回纵向,尺寸改变为在横向旋转回横向时应该改变的尺寸让我得到纵向尺寸。

然后我重新启动了应用程序,纵向旋转到横向,正如预期的那样,尺寸没有改变,然后我旋转到横向左侧,尺寸变成了正确的值。

所以显然代码有效,但只有在我改变场景后旋转场景时,尺寸才会真正改变。有没有办法立即做出这种改变?或者也许有更好的方法在旋转时改变场景大小?甚至有没有办法在不改变场景大小的情况下保持线条大小和相对于屏幕的位置?

标签: iosswiftsprite-kitskscene

解决方案


我通过将代码更改为:

 var scene: FractalTreeScene!
    override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {

        if UIApplication.shared.statusBarOrientation.isLandscape {
            scene.size = CGSize(width: 1337, height: 750)
        } else {
            scene.size = CGSize(width: 750, height: 1337)
        }
        scene.drawTree()
    }
    override func viewDidLoad() {
        super.viewDidLoad()


        if let view = self.view as! SKView? {
            // Load the SKScene from 'GameScene.sks'
            scene = FractalTreeScene()
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            if UIApplication.shared.statusBarOrientation.isLandscape{
                scene.size = CGSize(width: 1337, height: 750)
            } else {
                scene.size = CGSize(width: 750, height: 1337)
            }
            // Present the scene
            view.presentScene(scene)

            view.ignoresSiblingOrder = true

            view.showsFPS = true
            view.showsNodeCount = true
        }
    }

推荐阅读