为什么我的相机不居中?

时间:2016-02-10 04:17:30

标签: ios swift sprite-kit

我注意到我的camera SKScene属性为nil。我通过创建等于SKCameraNode属性的camera设置,设置其position并将其添加到场景中来解决这个问题。但是,当我这么做时,我的物体不再处于场景的中心。他们都以某种方式转移,这对我来说没有意义。我做错了什么?

class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/*
        // This is the problem code
        let cam = SKCameraNode()
        cam.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
        self.camera = cam
        self.addChild(cam)
*/
        let sprite = SKSpriteNode(imageNamed:"Spaceship")
        sprite.xScale = 0.5
        sprite.yScale = 0.5
        sprite.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
        self.addChild(sprite)

    }
}

对象出现在场景的中间,正如预期的那样。

Object in middle, as expected

现在对象向左移动。为什么呢?

Object shifted to the left

更新

以下代码给了我想要的行为。关键是每当SKScene的大小发生变化时重新定位相机。感谢您的建议,他们让我走上正轨。

class GameScene: SKScene {

override func didChangeSize(oldSize: CGSize) {
        if let view = self.view{
            camera?.position = convertPointFromView(view.center)
        }
    }

override func didMoveToView(view: SKView) {

        let cam = SKCameraNode()
        cam.position = CGPoint(x: frame.midX, y:frame.midY)
        self.camera = cam
        self.addChild(cam)
        let sprite = SKSpriteNode(imageNamed:"Spaceship")
        sprite.xScale = 0.5
        sprite.yScale = 0.5
        sprite.position = CGPoint(x: frame.midX, y: frame.midY)
        self.addChild(sprite)
    }
}

0 个答案:

没有答案