【问题标题】:iOS Swift - making an object respond to pan/slide Touch GesturesiOS Swift - 使对象响应平移/滑动触摸手势
【发布时间】:2014-10-13 19:27:42
【问题描述】:

我正在尝试制作我的第一个 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)
}

【问题讨论】:

    标签: ios swift touch


    【解决方案1】:

    您似乎对 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
            }
        }
    
    }
    

    【讨论】:

    • 嗨,我试过了,但我得到了这个:无法将表达式的类型“()”转换为类型“CGPoint”
    • 我猜是因为位置!
    • 抱歉,我太快了。我编辑了我的答案。这有帮助吗?
    • Hmm.. 仍然认为 'CGPoint' 不能转换为 'Double' 那是因为我在做这只鸟?.deltaPosY = 位置 deltaPosY 是双倍
    • 如果您要设置单个坐标,请尝试:bird?.deltaPosY = position.y
    【解决方案2】:

    这是有效的代码。

    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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2016-05-15
      相关资源
      最近更新 更多