将相机置于 swift spritekit 中的节点中心

Centering the camera on a node in swift spritekit

我正在 Swift 中创建泰拉瑞亚风格的游戏。我想要它让玩家节点始终位于屏幕中央,当您向右移动时,方块会像在泰拉瑞亚中一样向左移动。

我目前正在尝试弄清楚如何使视图以角色为中心。有谁知道完成这个的好方法吗?

您必须创建包含节点的世界节点。你应该放 anchorPoint 例如 (0.5,0.5)。以您的播放器为中心。然后你应该移动你的播放器。

func centerOnNode(node:SKNode){

   let cameraPositionInScene:CGPoint = self.convertPoint(node.position, fromNode: world!)
   world!.position = CGPoint(x:world!.position.x - cameraPositionInScene.x, y: world!.position.y - cameraPositionInScene.y)
}


override func didSimulatePhysics() {
  self.centerOnNode(player!)
}

下面将把相机放在特定节点的中心。它还可以在设定的时间范围内平滑地过渡到新位置。

class CameraScene : SKScene {
    // Flag indicating whether we've setup the camera system yet.
    var isCreated: Bool = false
    // The root node of your game world. Attach game entities 
    // (player, enemies, &c.) to here.
    var world: SKNode?
    // The root node of our UI. Attach control buttons & state
    // indicators here.
    var overlay: SKNode?
    // The camera. Move this node to change what parts of the world are visible.
    var camera: SKNode?

    override func didMoveToView(view: SKView) {
        if !isCreated {
            isCreated = true

            // Camera setup
            self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            self.world = SKNode()
            self.world?.name = "world"
            addChild(self.world)
            self.camera = SKNode()
            self.camera?.name = "camera"
            self.world?.addChild(self.camera)

            // UI setup
            self.overlay = SKNode()
            self.overlay?.zPosition = 10
            self.overlay?.name = "overlay"
            addChild(self.overlay)
        }
    }


    override func didSimulatePhysics() {
        if self.camera != nil {
            self.centerOnNode(self.camera!)
        }
    }

    func centerOnNode(node: SKNode) {
        let cameraPositionInScene: CGPoint = node.scene.convertPoint(node.position, fromNode: node.parent)

        node.parent.position = CGPoint(x:node.parent.position.x - cameraPositionInScene.x, y:node.parent.position.y - cameraPositionInScene.y)
    }

}

通过移动相机更改世界中的可见内容:

// Lerp the camera to 100, 50 over the next half-second.
self.camera?.runAction(SKAction.moveTo(CGPointMake(100, 50), duration: 0.5))

来源:swiftalicio - 2D Camera in SpriteKit

有关更多信息,请查看 Apple 的 SpriteKit Programming Guide(示例:在节点上居中场景)。

由于 iOS 9 / OS X 10.11 / tvOS,SpriteKit 包含 SKCameraNode,这使得很多事情变得更容易:

  • 定位相机节点会自动调整视口
  • 你可以很容易地rotate/zoom通过在相机节点中变换相机
  • 您可以通过使 HUD 元素成为相机节点的子节点来修复相对于屏幕的 HUD 元素
  • 场景的位置保持固定,因此当您通过移动世界来模拟相机时,物理关节之类的东西不会破坏它们的工作方式

当您将相机节点与另一个新功能 SKConstraint 结合使用时,效果会更好。您可以使用约束来指定相机的位置始终以角色为中心......或者添加额外的约束来说明,例如,相机的位置必须保持在世界边缘的某个边缘内。