以下代码识别场景的底部和顶部边缘,并且球按预期反弹.但是,场景的左右边缘始终被破坏.球离开屏幕然后如果施加足够的力则最终返回.就好像场景的边缘超出了
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 app dev和swift的新手,请原谅我,如果答案很明显,我就错过了.
最佳答案 你可能在关于.sks文件的正确轨道上.从.sks文件加载场景时,默认大小为1024×768.现在,您可以根据视图大小动态设置它.所以,将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的帖子,所以我会在答案中跳过这个帖子.
希望这可以帮助.