【问题标题】:How can I flick/swipe a sprite without dragging it?如何在不拖动的情况下轻弹/滑动精灵?
【发布时间】:2016-10-24 00:26:02
【问题描述】:

好的,目前在我的游戏中,我可以拖动、滑动和轻弹节点。但是,我希望用户只能滑动/轻拂节点,并且我不希望用户能够拖动节点。我该怎么做?

这是我当前的代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {
        let location = touch.location(in: self)

        if ball.frame.contains(location) {
            touchPoint = location
            touching = true
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first as UITouch!
    let location = touch!.location(in: self)
    touchPoint = location

    for touch in touches {
        let location = touch.location(in: self)
        touchPoint = location
        if touching {
            if touchPoint != ball.position {
                let dt:CGFloat = 1.0/60.0
                let distance = CGVector(dx: touchPoint.x-ball.position.x, dy: touchPoint.y-ball.position.y)
                let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt)
                ball.physicsBody!.velocity=velocity
            }
        }   
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    touching = false

    for touch in touches {
        let location = touch.location(in: self)
        touchPoint = location
        let node = self.atPoint(location)
    }
}

【问题讨论】:

  • 请更清楚地定义您想要实现的目标。
  • 我猜:您的目标是让节点在手指从滑动手势中释放之前不移动,此时手指在屏幕上移动的速率和距离决定了速率和节点的行进方向?

标签: ios swift sprite-kit game-physics


【解决方案1】:

这就是UIGestureRecognizers 存在的原因。在您的视图上添加UIPanGestureRecognizer,并使用velocity(in:UIView) 方法让您知道轻弹的方向和速度。

请注意,您不能将手势放在节点上,只能放在视图上,因此如果您只使用手势,则需要将视图坐标转换为场景坐标。

您还可以让手势的触摸向下渗透到场景中,以允许正常的触摸调用,并且只使用平移手势的速度。

https://developer.apple.com/reference/uikit/uipangesturerecognizer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2011-09-30
    • 2016-05-13
    • 2016-01-16
    相关资源
    最近更新 更多