如何在游戏场景中使用捏合手势

How to use pinch gesture in game scene

我需要你们的帮助。我有游戏场景和功能,允许使用 panGesture 移动相机。我还需要 pinchGesture 来放大和缩小我的 SKScene。我在这里找到了一些代码,但它滞后了。请问有人可以帮我改进这段代码吗? `

@objc private func didPinch(_ sender: UIPinchGestureRecognizer) {
            guard let camera = self.camera else {return}
            if sender.state == .changed {
                previousCameraScale = camera.xScale
            }
            camera.setScale(previousCameraScale * 1 / sender.scale)
            sender.scale = 1.0
        }

`

试试这个捏代码。

//pinch -- simple version
@objc func pinch(_ recognizer:UIPinchGestureRecognizer) {
    guard let camera = self.camera else { return } // The camera has a weak reference, so test it
    
    if recognizer.state == .changed {
        let deltaScale = (recognizer.scale - 1.0)*2
        let convertedScale = recognizer.scale - deltaScale
        let newScale = camera.xScale*convertedScale
        camera.setScale(newScale)
        
        //reset value for next time
        recognizer.scale = 1.0
    }
}

虽然我会推荐这个稍微复杂一点的版本,它以触摸点为中心。使我的体验更好。

//pinch around touch point
@objc func pinch(_ recognizer:UIPinchGestureRecognizer) {
    guard let camera = self.camera else { return } // The camera has a weak reference, so test it

    //cache location prior to scaling
    let locationInView = recognizer.location(in: self.view)
    let location = self.convertPoint(fromView: locationInView)
    
    if recognizer.state == .changed {
        let deltaScale = (recognizer.scale - 1.0)*2
        let convertedScale = recognizer.scale - deltaScale
        let newScale = camera.xScale*convertedScale
        camera.setScale(newScale)
        
        //zoom around touch point rather than center screen
        let locationAfterScale = self.convertPoint(fromView: locationInView)
        let locationDelta = location - locationAfterScale
        let newPoint = camera.position + locationDelta
        camera.position = newPoint
        
        //reset value for next time
        recognizer.scale = 1.0
    }
}

//also need these extensions to add and subtract CGPoints
extension CGPoint { 
  static func + (a:CGPoint, b:CGPoint) -> CGPoint {
      return CGPoint(x: a.x + b.x, y: a.y + b.y)
  }   

  static func - (a:CGPoint, b:CGPoint) -> CGPoint {
      return CGPoint(x: a.x - b.x, y: a.y - b.y)
  }
}