Center camera on node in fast spritekit

I am creating a Terraria-style game in Swift. I want the node player to always be in the center of the screen, and when you move to the right, the blocks go to the left, as in Terraria.

I'm currently trying to figure out how to keep the idea in the spotlight of a character. Does anyone know of a good way to accomplish this?

+4
source share
3 answers

Below is an image of a camera on a specific node. It can also smoothly move to a new position within a given time interval.

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 the visibility 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

Apple SpriteKit (: Node).

+5

iOS 9/OS X 10.11/tvOS, SpriteKit SKCameraNode, :

  • node
  • / node
  • HUD , node
  • , , , , , .

, , SKConstraint. , , ... , , .

+6

You need to create a World node containing the nodes. And you should put anchorPointfor example (0.5.0.5). Center on your player. And then you have to move your player.

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!)
}
0
source

All Articles