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

bob*_*bob 4 sprite-kit swift

我在斯威夫特创造了一个Terraria风格的游戏.我想拥有它,所以玩家节点总是在屏幕的中心,当你向右移动时,这些块就像Terraria一样向左移动.

我目前正在试图弄清楚如何将视图保持在角色的中心.有谁知道实现这个的好方法?

ric*_*ter 6

自从iOS 9/OS X 10.11/tvOS,SpriteKit包含SKCameraNode,这使得这很容易:

  • 定位摄像机节点会自动调整视口
  • 您可以通过在摄像机节点中进行变换来轻松旋转/缩放摄像机
  • 您可以通过使HUD元素成为相机节点的子项来修复相对于屏幕的HUD元素
  • 场景的位置保持固定,因此像物理关节这样的东西不会破坏他们通过移动世界模拟相机时的方式

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


san*_*ony 5

以下将使相机居中于特定节点.它还可以在设定的时间范围内平滑过渡到新位置.

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)
    }

}
Run Code Online (Sandbox Code Playgroud)

通过移动相机来改变世界上可见的内容:

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

来源:swiftalicio - SpriteKit中的2D相机

有关其他信息,请参阅 Apple的SpriteKit编程指南(示例:在节点上居中显示场景).