Swift SpriteKit edgeLoopF​​romRect问题

以下代码可以识别场景的底部和顶部边缘 ,并按预期方式弹起球。 但是,场景的左右边缘始终被破坏。 球离开屏幕,然后如果施加足够的力量,最终返回。 就好像场景的边缘超出了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文件的维度? 这样它将是dynamic的,可以在不同的设备上工作。

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

我在这里发现了同样的问题,但从来没有回答过: Swift物理边缘识别问题

此外,我是新的iOS应用程序开发和迅速,所以原谅我,如果答案是明显的,我错过了。

您可能在正确的轨道.sks文件。 从.sks文件加载场景时,默认大小为1024×768。 现在,您可以根据视图大小dynamic设置。 所以,用viewWillLayoutSubviewsreplace你的viewDidLoad,像这样:

 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上有很多关于viewDidLoad和viewWillLayoutSubviews之间差异的post,所以我会在我的答案中略过。

希望这可以帮助。