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
}
分类:
SpriteKit
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)