我有SKSpriteNode
我希望通过touchesMoved
在屏幕上拖动。但是,如果触摸没有首先出现在精灵的位置(不跳过场景),我不希望精灵移动。
我有一个间歇性的解决方案但是相信某些东西更优雅,更实用,因为这个解决方案无法正常工作 - 如果用户没有跟上触摸位置,就好像精灵位置一样快速拖动精灵。
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
var touchPoint : CGPoint = location
var muncherRect = muncherMan.frame
if (CGRectContainsPoint(muncherRect, touchPoint)) {
muncherMan.position = location
} else {
}
}
}
答案 0 :(得分:2)
您可以实现这三种方法来实现您的目标:touchesBegan
,touchesMoved
和touchesEnded
。触摸muncherMan
后,将muncherManTouched
设置为true,表示muncherMan
可能会在下一帧中移动。完成移动或触摸时,将muncherManTouched
设置为false并等待下一次触摸。
这是示例代码。我为muncherMan
添加了一个名称,以便我们可以确定touchesBegan
中要触摸的节点。
var muncherManTouched = false
override func didMoveToView(view: SKView) {
/* Setup your scene here */
...
muncherMan.name = "muncherMan"
self.addChild(muncherMan)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let nodeTouched = self.nodeAtPoint(location)
if (nodeTouched.name == "muncherMan") {
muncherManTouched = true
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
if (muncherManTouched == true) {
muncherMan.position = location
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
muncherManTouched = false
}