SKCameraNode
- 当场景的尺寸需要超过屏幕,需要移动或者缩放去查看更多界面时,就可以是使用 SKCameraNode。
- 在 SKScene 中使用。SKScene 中的 camera 属性默认是 nil。需要自己去初始化赋值。
- SKCameraNode 的缩放比例是小于1放大,大于1缩小
lazy var myCamera = SKCameraNode()
override func didMove(to view: SKView) {
super.didMove(to: view)
myCamera.position = CGPoint(x: view.bounds.width * 0.5, y: view.bounds.height * 0.5)
self.addChild(myCamera)
self.camera = myCamera
}
移动镜头
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let touch = touches.first else {
return
}
let locPoint = touch.location(in: self)
let prePoint = touch.previousLocation(in: self)
let x = myCamera.position.x - (locPoint.x - prePoint.x)
let y = myCamera.position.y - (locPoint.y - prePoint.y)
let point = CGPoint(x: x, y: y)
print("point:\(point)")
self.camera?.position = point
}
缩放视图
var tempScale: CGFloat?
lazy var cameraScale: CGFloat = 1 {
didSet {
myCamera.xScale = cameraScale
myCamera.yScale = cameraScale
}
}
let minScale: CGFloat = 2
let maxScale: CGFloat = 0.5
override func didMove(to view: SKView) {
super.didMove(to: view)
let pinchGes = UIPinchGestureRecognizer(target: self, action: #selector(pinchGestureAction(pinchGes:)))
view.addGestureRecognizer(pinchGes)
}
@objc func pinchGestureAction(pinchGes: UIPinchGestureRecognizer) {
let location = pinchGes.location(in: self.view)
let cameraLocation = self.convertPoint(fromView: CGPoint(x: -location.x, y: -location.y))
let scale = pinchGes.scale
let velocity = pinchGes.velocity
switch pinchGes.state {
case .began:
pinchBeganAtLocation(loc: cameraLocation, scale: scale, velocity: velocity)
case .changed:
pinchChangedAtLocation(loc: cameraLocation, scale: scale, velocity: velocity)
case .ended:
pinchEndedAtLocation(loc: cameraLocation, scale: scale, velocity: velocity)
default:
break
}
}
func pinchBeganAtLocation(loc: CGPoint, scale: CGFloat, velocity: CGFloat) {
tempScale = scale
}
func pinchChangedAtLocation(loc: CGPoint, scale: CGFloat, velocity: CGFloat) {
guard let tempScale = tempScale else {
return
}
let deltaScale = (tempScale - scale)
var lastScale = cameraScale
lastScale += deltaScale
if lastScale <= maxScale {
lastScale = maxScale
} else if lastScale >= minScale {
lastScale = minScale
}
cameraScale = lastScale
self.tempScale = scale
}
func pinchEndedAtLocation(loc: CGPoint, scale: CGFloat, velocity: CGFloat) {
tempScale = nil
}
标签:SKCameraNode,self,SpriteKit,scale,let,velocity,myCamera,CGFloat
From: https://www.cnblogs.com/shen5214444887/p/16805296.html