sprite-kit SKScene Create an SKScene with an SKCameraNode (iOS 9 and later)

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

You can place an SKCameraNode into an SKScene to define which part of the scene is shown in the SKView. Think of the SKScene as a 2D world with a camera floating above it: the SKView will show what the camera 'sees'.

E.g. the camera could be attached to the main character's sprite to follow the action of a scrolling game.

The SKCameraNode has four parameters that define what part of the scene is shown:

  • position: this is the position of the camera in the scene. The scene is rendered to place this position in the middle of the SKView.
  • xScale and yScale: these define how the scene is zoomed in the view. Keep these two values the same to avoid distorting the view. A value of 1 means no zoom, values less than one will zoom in (make the sprites appear larger) and values above 1 will zoom out (make the sprites appear smaller).
  • zRotation: this defines how the view is rotated in the view. A value of zero will be no rotation. The value is in radians, so a value of Pi (3.14...) will rotate the view upside-down.

The following code assumes an SKView called skView already exists (e.g. as defined in Create a Full Screen SKView using Interface Builder) and a subclass of SKScene called GameView has been defined. This example just sets the camera's initial position, you would need to move the camera (in the same way as you would other SKSpriteNodes in the scene) to scroll your view:

In Swift 3:

    let sceneSize = CGSize(width:1000, height:1000)
    let scene = GameScene(size: sceneSize)
    scene.scaleMode = .aspectFill

    let camera = SKCameraNode()
    camera.position = CGPointM(x:500, y:500)
    camera.xScale = 1
    camera.yScale = 1
    camera.zRotation = 3.14
    scene.addChild(camera)
    scene.camera = camera

    skView.presentScene(scene)


Got any sprite-kit Question?