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

2

14

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

Pegasus answered 18/8, 2015 at 17:31 Comment(1)
What's wrong with setting the world's scale property? If you're targeting iOS 9, you can add an SKCameraNode.Pilatus
P
56

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/

Psychosexual answered 1/12, 2015 at 18:5 Comment(1)
Cool, I'll give that a try. ThanksPegasus
P
-1

So, the best solution I could could find goes something like this. In the didMoveToView function, create an SKSpriteNode called World and make it whatever size you want your world to be. Then, write world.setScale(0.5) if you want a 50% zoom-out. However, if you have a player node that needs to always be centered in the screen, you'll need to add the following to your update function.

override func update(currentTime: CFTimeInterval) {
    world.position.x = -player.position.x * (0.5)
    world.position.y = -player.position.y * (0.5)
}
Pegasus answered 19/8, 2015 at 0:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.