如何限制 SpriteKit 中的缩放

How to limit zooming in SpriteKit

我有一个 Swift + SpriteKit 应用程序,它将 SKSpriteNode 加载到场景中,注册 UIPinchGestureRecognizer,并使用简单的处理函数处理捏合手势,如下所示:

func zoom(_ sender: UIPinchGestureRecognizer) {

    // Don't let the map get too small or too big:
    if map.frame.width >= 1408 && map.frame.width <= 3072 {
        map.run(SKAction.scale(by: sender.scale, duration: 0))
    }

    print(map.frame.width)
}

但是,捏合仍会使 sprite 节点的大小小于指定的限制,然后当我尝试再次松开捏合时,处理程序突然识别出我设置的限制并且不会允许和取消-捏手势。

我试过用识别器的比例属性做同样的事情:

func zoom(_ sender: UIPinchGestureRecognizer) {

    // Don't let the map get too small or too big:
    if sender.scale >= 0.9 && sender.scale <= 2.1 {
        map.run(SKAction.scale(by: sender.scale, duration: 0))
    }
    print(map.frame.width)
}

但这更奇怪:精灵节点将在收缩时停止变小,但在松开时会变得非常大。

在捏合手势上设置界限的正确方法是什么?

这是我想出的解决方案,但有一件事我不喜欢它:

func zoom(_ sender: UIPinchGestureRecognizer) {

    // If the height of the map is already <= the screen height, abort pinch
    if (sender.scale < 1) {
        if (true) { print("pinch rec scale = \(sender.scale)") }
        if (map.frame.width <= 1408) {
            if (true) { print("Pinch aborted due to map height minimum.") }
            return
        }
    }

    // If the height of the map is already >= 2000 the screen height, abort zoom
    if (sender.scale > 1) {
        if (true) { print("pinch rec scale = \(sender.scale)") }
        if (map.frame.width >= 3072) {
            if (true) { print("Pinch aborted due to map height Max.") }
            return;
        }
    }

    map.run(SKAction.scale(by: sender.scale, duration: 0))
    sender.scale = 1;
}

如果您执行快速收缩,地图节点可能会减小到比 if 语句中的限制所规定的小得多的大小。如果您以正常速度(无论如何不是超快)执行捏合,则遵守 if 语句中规定的限制。

我不知道如何处理这种情况。