Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpriteKit pinch to zoom camera

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

like image 394
Brejuro Avatar asked Jun 02 '17 19:06

Brejuro


1 Answers

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.

like image 196
Steve G. Avatar answered Nov 13 '22 06:11

Steve G.