簡體   English   中英

將相機置於swift spritekit中的節點上

[英]Centering the camera on a node in swift spritekit

我在斯威夫特創造了一個Terraria風格的游戲。 我想擁有它,所以玩家節點總是在屏幕的中心,當你向右移動時,這些塊就像Terraria一樣向左移動。

我目前正在試圖弄清楚如何將視圖保持在角色的中心。 有誰知道實現這個的好方法?

從iOS 9 / OS X 10.11 / tvOS開始,SpriteKit包含了SKCameraNode ,它使這很容易:

  • 定位攝像機節點會自動調整視口
  • 您可以通過在攝像機節點中進行變換來輕松旋轉/縮放攝像機
  • 您可以通過使HUD元素成為相機節點的子項來修復相對於屏幕的HUD元素
  • 場景的位置保持固定,因此像物理關節這樣的東西不會破壞他們通過移動世界模擬相機時的方式

將攝像機節點與另一個新功能SKConstraint結合使用時會更好。 您可以使用約束來指定攝像機的位置始終以角色為中心...或者添加額外的約束,例如,攝像機的位置必須保持在世界邊緣的某個邊緣內。

以下將使相機居中於特定節點。 它還可以在設定的時間范圍內平滑過渡到新位置。

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 - SpriteKit中的2D相機

有關其他信息,請參閱 Apple的SpriteKit編程指南 (示例:在節點上居中顯示場景)。

您必須創建包含節點的World節點。 你應該把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!)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM