Aid*_*ser 5 camera pan sprite-kit skscene swift
我正在使用swift在sprite kit中创建一个游戏,我试图用手指移动SKScene,因为并非所有节点都适合场景.我已经使用此代码创建了世界,叠加和相机节点.
override func didMoveToView(view: SKView) {
world = self.childNodeWithName("world")!
if !isCreated {
isCreated = true
// Camera setup
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.world = SKNode()
self.world.name = "world"
addChild(self.world)
self.cam = SKNode()
self.cam.name = "camera"
self.world.addChild(self.cam)
// UI setup
self.overlay = SKNode()
self.overlay.zPosition = 10
self.overlay.name = "overlay"
addChild(self.overlay)
}
Run Code Online (Sandbox Code Playgroud)
我希望能够用一根手指使用平移手势来移动相机.我该怎么做?任何帮助,将不胜感激.
作为@Kris解决方案(基于UIKit)的替代方法,您还可以使用SKScene子类监视Sprite Kit中的触摸。我写了一个小样本,应该为您指明正确的方向。
class YourSceneSubclass : SKScene
{
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else {
return
}
let location = touch.locationInNode(self)
let previousLocation = touch.previousLocationInNode(self)
camera?.position.x += location.x - previousLocation.x
camera?.position.y += location.y - previousLocation.y
}
}
Run Code Online (Sandbox Code Playgroud)
我没有运行它,只是在操场上写了它。还要注意,如果您还想处理其他敲击/手势,则必须编写其他代码,以确保识别能够在所有预期的情况下正常工作。
如果有人需要,这是一个多合一的解决方案:
class GameScene: SKScene {
var previousCameraPoint = CGPoint.zero
override func didMove(to view: SKView) {
let panGesture = UIPanGestureRecognizer()
panGesture.addTarget(self, action: #selector(panGestureAction(_:)))
view?.addGestureRecognizer(panGesture)
}
@objc func panGestureAction(_ sender: UIPanGestureRecognizer) {
// The camera has a weak reference, so test it
guard let camera = self.camera else {
return
}
// If the movement just began, save the first camera position
if sender.state == .began {
previousCameraPoint = camera.position
}
// Perform the translation
let translation = sender.translation(in: self.view)
let newPosition = CGPoint(
x: previousCameraPoint.x + translation.x * -1,
y: previousCameraPoint.y + translation.y
)
camera.position = newPosition
}
}
Run Code Online (Sandbox Code Playgroud)