Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpriteKit- How to zoom-in and zoom-out of an SKScene?

If I'm making a game in SpriteKit that has a large "world", and I need the user to have the option of zooming in and out of the SKScene, how would I go about this? Or, to make things simpler, in the didMoveToView function, how can I present more of the world to the user's device's screen (without using world.runAction(SKAction.scaleTo(0.5)) or something)?

like image 270
Austin Avatar asked Aug 18 '15 17:08

Austin


1 Answers

There's a SKCameraNode that's built specifically for this. The SKCameraNode defines the viewport into your scene. You create a camera node and assign it to the camera property of your scene.

let cameraNode = SKCameraNode()
cameraNode.position = CGPoint(x: scene.size.width / 2, scene.size.height / 2)
scene.addChild(cameraNode)
scene.camera = cameraNode

You can then create actions and run those actions on the camera. So to zoom in on the scene, you'd do this.

    let zoomInAction = SKAction.scale(to: 0.5, duration: 1)
    cameraNode.run(zoomInAction)

The cameraNode basically is a square node in the scene, that I think takes the proportions of the view by default? Cuz there's no size initializer. So when you make it smaller, the scene looks like it gets zoomed. To zoom out you'd make an action that increases the scale. Basically imagine a rectangle on your entire scene, and whatever is in the cameraNode's rectangle directly shows on your iPhone screen. You can also add moveTo actions and sequence actions and set timingModes on the actions same as if it were your normal spriteNode.

Here's the WWDC where the apple guy shows what I've just said. CameraNode bit is around 3 mins before the end.

https://developer.apple.com/videos/play/wwdc2015-604/

like image 134
Peter Parker Avatar answered Sep 28 '22 18:09

Peter Parker