iOS Swift - 使对象响应平移/滑动触摸手势

时间:2014-10-13 19:27:42

标签: ios swift touch

我正在尝试制作我的第一款iOS游戏。由于我是编程新手,特别是在Swift中,这对我来说非常困难。

我想让我的卡通老鹰回应我的手指滑动(我想要做的是在屏幕上的任何地方滑动我的手指,我的老鹰会对此作出反应)。

我已经完成了它,所以我可以移动它,但我想做的只是在屏幕上的任何地方滑动手指,老鹰对我手指的动作作出反应。

到目前为止,这是我的代码,我在故事板中将它与PanGestureRecognizer相关联:

  @IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
    let translation = recognizer.translationInView(self.view)
    recognizer.view!.center = CGPoint(x:recognizer.view!.center.x + translation.x,
        y:recognizer.view!.center.y + translation.y)
    recognizer.setTranslation(CGPointZero, inView: self.view)
}

2 个答案:

答案 0 :(得分:2)

您似乎对UIKit和SpriteKit感到困惑。

基本上,您需要做的是在屏幕上移动时跟踪您的触摸。由于SKNode继承自UIResponder,最简单的方法是覆盖:

touchesBegan(_:withEvent:)
touchesMoved(_:withEvent:)
touchesEnded(_:withEvent:)

例如,让鸟节点跟随你的手指:

class YourScene : SKScene {

    var birdNode: BirdNode

    // Additional setup, etc

    override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
        super.touchesMoved(touches, withEvent: event)
        if touches.count > 0 {
            var touch: UITouch = touches.anyObject()! as UITouch
            var position: CGPoint = touch.locationInView(self.view)
            position = self.convertPointFromView(position)
            birdNode.position = position
        }
    }

}

答案 1 :(得分:1)

这是有效的代码。

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesMoved(touches, withEvent: event)

    if (touches.count > 0) {
        var touch = touches.first as! UITouch
        var position = touch.locationInView(view)
        println(position.x)
        println(position.y)
    }
}
相关问题