在SpriteKit Swift中移动相机 [英] Moving Camera in SpriteKit Swift
问题描述
我正在使用swift在Sprite Kit中创建游戏,并且我试图能够用手指移动SKScene,因为并非所有节点都适合场景.我已经使用此代码创建了world,overlay和camera节点.
I am creating a game in sprite kit using swift, and I am trying to be able to move the SKScene around with a finger because not all of the nodes fit within the scene. I have already created world, overlay, and camera nodes with this code.
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)
}
我希望能够通过使用一根手指的平移手势来移动摄像机.我该怎么做?任何帮助将不胜感激.
I would like to be able to move the camera around by using a pan gesture with a single finger. How would I do this? Any help would be appreciated.
推荐答案
作为@Kris解决方案(基于UIKit)的替代方案,您还可以使用SKScene子类监视Sprite Kit中的触摸.我写了一个小样本,应该为您指明正确的方向.
As an alternative to @Kris's solution (which is based in UIKit), you can also monitor touches in Sprite Kit with your SKScene subclass. I wrote a small sample which should point you in the right direction.
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
}
}
我没有运行它,只是在操场上写了它.另外请注意,如果您还想处理其他敲击/手势,则必须编写其他代码,以确保识别能够在所有预期的情况下正常工作.
I didn't run this, just wrote it in a playground. Also note that if you want to handle other taps/gestures as well you will have to write additional code making sure the recognition works well for all your intended scenarios.
这篇关于在SpriteKit Swift中移动相机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!