I can't seem to find anywhere how to implement a camera pinch to zoom in SpriteKit.
In my GameScene I can seem to run a zoom in action on the camera with:
let cameraNode = SKCameraNode()
cameraNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
addChild(cameraNode)
camera = cameraNode
let zoomInAction = SKAction.scale(to: 0.5, duration: 1)
cameraNode.run(zoomInAction)
But I can't seem to figure out how to translate this to a pinch to zoom feature
Here is a solution that worked for me, using gesture recognizers:
class GameScene: SKScene {
var previousCameraScale = CGFloat()
override func sceneDidLoad() {
let pinchGesture = UIPinchGestureRecognizer()
pinchGesture.addTarget(self, action: #selector(pinchGestureAction(_:)))
view?.addGestureRecognizer(pinchGesture)
}
@objc func pinchGestureAction(_ sender: UIPinchGestureRecognizer) {
guard let camera = self.camera else {
return
}
if sender.state == .began {
previousCameraScale = camera.xScale
}
camera.setScale(previousCameraScale * 1 / sender.scale)
}
}
You can easily define a min and a max for the camera scale, and use your bounds on the calculous if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With