Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make camera follow SKNode in Sprite Kit?

Tags:

ios

sprite-kit

I want to have background stationary with different objects (sprites and other objects).

Player will be represented by center node that will move around the world. I want to have my camera pinned to central node, e.g. the world should move and the camera should stay stationary.

How do I achieve that?

like image 694
Dvole Avatar asked Dec 29 '13 18:12

Dvole


2 Answers

The new SKCameraNode seems like a very easy way to do this.

https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKCameraNode/

Simply

1) create an SKCameraNode

// properties of scene class
let cam = SKCameraNode()
let player = SKSpriteNode()

2) add it to your scene camera property

// In your scene, for instance didMoveToView
self.camera = cam

3) make the camera follow your player position

override func update(currentTime: CFTimeInterval)
{
    /* Called before each frame is rendered */
    cam.position = player.position
}
like image 74
OwlOCR Avatar answered Sep 16 '22 19:09

OwlOCR


Using SKCameraNode with SKConstraint in Swift 5.1

let camera = SKCameraNode()
camera.constraints = [.distance(.init(upperLimit: 10), to: node)]
scene.addChild(camera)
scene.camera = camera
like image 26
vauxhall Avatar answered Sep 20 '22 19:09

vauxhall