【问题标题】:Swift SpriteKit edgeLoopFromRect IssueSwift SpriteKit edgeLoopF​​romRect 问题
【发布时间】:2015-06-14 23:49:54
【问题描述】:

以下代码可识别场景的底部和顶部边缘,并且球按预期反弹。然而,场景的左右边缘总是被破坏。如果施加足够的力,球会离开屏幕,然后最终返回。就好像场景的边缘超出了 iphone 模拟器窗口的边缘。

import SpriteKit

class GameScene: SKScene {
    override func didMoveToView(view: SKView){
        self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
        backgroundColor = UIColor.cyanColor()
        var ball = SKSpriteNode(imageNamed: "ball")
        ball.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        self.addChild(ball)
        ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.height/2)
        let push = CGVectorMake(10, 10)
        ball.physicsBody.applyImpulse(push)

    }
}

我认为这与 .sks 文件有关,因为在那里设置了尺寸,如果我更改这些尺寸,它会反映在游戏中。任何人都知道如何做到这一点,所以这行代码优先于 .sks 文件尺寸?这样,它将是动态的,并且可以在不同的设备上运行。

self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)

我在这里发现了同样的问题,但从未得到回答: Swift physicsbody edge recognition issue

另外,我是 iOS 应用程序开发的新手,如果答案很明显而我错过了,请原谅我。

【问题讨论】:

    标签: ios swift sprite-kit cgrect skphysicsbody


    【解决方案1】:

    关于 .sks 文件,您可能走在正确的轨道上。从 .sks 文件加载场景时,默认大小为 1024x768。现在您可以根据视图大小动态设置它。因此,将 viewDidLoad 与 viewWillLayoutSubviews 交换,如下所示:

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    
        if let scene = GameScene(fileNamed:"GameScene") {
            // Configure the view.
            let skView = self.view as! SKView
            skView.showsFPS = true
            skView.showsNodeCount = true
    
            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true
    
            //Because viewWillLayoutSubviews might be called multiple times, check if scene is already initialized
             if(skView.scene == nil){
    
                /* Set the scale mode to scale to fit the window */
                scene.scaleMode = .AspectFill
                scene.size = skView.bounds.size
    
                skView.presentScene(scene)
            }
        }
    }
    

    SO 上有很多关于differences between viewDidLoad and viewWillLayoutSubviews 的帖子,所以我将在我的回答中跳过它。

    希望这会有所帮助。

    【讨论】:

    • 感谢您的帮助,是的,这似乎有效!是的,我会研究这种差异,以便更好地理解。
    • @GusGus 不客气 :) 这是另一个教程,它甚至用图片来描述这个......ymc.ch/en/ios-7-sprite-kit-setting-up-correct-scene-dimensions。但我建议您仔细阅读我在答案中发布的链接,因为它有更多关于这一切的详细信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多