Centering the camera on a node in swift spritekit

前端 未结 3 1383
北恋
北恋 2021-02-10 22:19

I am creating a Terraria-style game in Swift. I want to have it so the player node is always in the center of the screen, and when you move right the blocks go left like in Terr

3条回答
  •  我寻月下人不归
    2021-02-10 22:43

    The below will center the camera on a specific node. It can also smoothly transition to the new position over a set time frame.

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

    Change what’s visible in the world by moving the camera:

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

    Source: swiftalicio - 2D Camera in SpriteKit

    For additional information, look at Apple's SpriteKit Programming Guide (Example: Centering the Scene on a Node).

提交回复
热议问题