ios - Swift SpriteKit edgeLoopF​​romRect 问题

标签 ios swift sprite-kit cgrect skphysicsbody

以下代码识别场景的底部和顶部边缘,并且球按预期反弹。然而,场景的左边缘和右边缘总是被破坏。如果施加足够的力,球会离开屏幕然后最终返回。就好像场景的边缘超出了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 文件有关,因为尺寸是在那里设置的,如果我改变这些尺寸,它会反射(reflect)在游戏中。任何人都知道如何使这行代码优先于 .sks 文件尺寸?这样它将是动态的并且可以在不同的设备上工作。

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

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

此外,我是 iOS 应用程序开发新手并且速度很快,如果答案很明显但我错过了,请原谅我。

最佳答案

关于 .sks 文件,您可能走在正确的轨道上。从 .sks 文件加载场景时,默认大小为 1024x768。现在您可以根据 View 大小动态设置它。因此,像这样将 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的帖子,所以我会在我的回答中跳过它。

希望这对您有所帮助。

关于ios - Swift SpriteKit edgeLoopF​​romRect 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30835728/

相关文章:

swift - 运行完成 : after sequence or group of SKActions

iOS模拟器声音

ios - 内部使用 self 的队列调用方法上的 weakSelf

ios - 在 uipageviewcontroller 的第一个 View 和最后一个 View 中禁用滑动

ios - Swiftui:如何在导航标题上添加辅助功能标识符

swift - SKScene 的左下角坐标

ios - 如何在 TableView 中显示全局字典项

ios - 如何使用 Realm 通知来检测嵌套 Realm 对象的更改

ios - 我如何告诉 RxSwift 做某事,无论成功或失败

ios - 遍历 SKNode 的所有子节点?