【问题标题】:Getting a vector from a touch location in swift 3从swift 3中的触摸位置获取矢量
【发布时间】:2016-10-25 19:08:44
【问题描述】:

正如标题所说,我怎样才能做到这一点?我可以进行第一次触摸,但如果是滑动手势,我不知道如何进行最后一次触摸。使用以下代码,我得到错误:“Set”类型的值没有成员“last”。不确定如何在释放触摸时获得位置。

override func touchesMoved(_ touches: Set<UITouch>, with: UIEvent?){
    let firstTouch:UITouch = touches.first! as UITouch
    let lastTouch:UITouch = touches.last! as UITouch

    let firstTouchLocation = firstTouch.location(in: self)
    let lastTouchLocation = lastTouch.location(in: self)

}

我想获取第一个点的位置和第二个点的位置。然后我想使用滑动的持续时间、线条的大小和线条的角度来创建一个脉冲向量以在 SKNode 上使用。有没有办法使用 UITouch 提取这些信息?任何帮助是极大的赞赏。感谢您的宝贵时间!

我在屏幕上也有基本的触摸来运行功能

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first! as UITouch
    let touchLocation = touch.location(in: self)
    if playButton.contains(touchLocation) && proceed == true{
        playSound1()
        Ball.physicsBody?.affectedByGravity = true
        proceed = false}
    else if infoButton.contains(touchLocation) && proceed == true{
        playSound1()
        loadScene2()}
    else {}
}

【问题讨论】:

  • touches 集合包含单个(开始/移动/结束)事件的所有手指触摸屏幕的位置,而不是动作的“开始”和“结束”位置。

标签: uikit swift3 uitouch uievent touchesended


【解决方案1】:

您必须存储 touches begin 中的值并与 touches end 中的值进行比较,然后在那里进行计算。请注意,触摸可以通过电话等方式取消,因此您也需要对此进行预测。

    class v: UIViewController {
        var startPoint: CGPoint?
        var touchTime = NSDate()
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            guard touches.count == 1 else {
                return
            }
            if let touch = touches.first {
                startPoint = touch.location(in: view)
                touchTime = NSDate()
            }
        }

        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            defer {
                startPoint = nil
            }
            guard touches.count == 1, let startPoint = startPoint else {
                return
            }
            if let touch = touches.first {
                let endPoint = touch.location(in: view)
                //Calculate your vector from the delta and what not here
                let direction = CGVector(dx: endPoint.x - startPoint.x, dy: endPoint.y - startPoint.y)
                let elapsedTime = touchTime.timeIntervalSinceNow
                let angle = atan2f(Float(direction.dy), Float(direction.dx))
            }
        }

        override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
            startPoint = nil
        }
    }

【讨论】:

  • 那么我要创建一个新的视图控制器类吗?你可以有多个视图控制器吗?或者我可以在我的菜单类中使用这些功能吗?我希望只需要在我的 GameScene 中计算这个向量,而不是在我的 MenuScene 中
猜你喜欢
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多