使用捏合手势限制手势

时间:2014-05-27 21:53:46

标签: ios sprite-kit uipangesturerecognizer uipinchgesturerecognizer

我正在使用Spritekit创建游戏,并使用Pan Gesture和Pinch Gesture来查看地图。目前我将Pinch Gesture的缩放限制为2.0。我试图将Pan Gesture限制在屏幕的边界,即使在缩放时也是如此。地图比屏幕大,我只希望用户能够平移,直到地图的外边缘到达屏幕的外边缘,即使在缩放时也是如此。这是我尝试处理这种情况的业余方式:

-(void) handlePanFrom:(UIPanGestureRecognizer*)recognizer {
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [recognizer setTranslation:CGPointZero inView:recognizer.view];
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [recognizer translationInView:recognizer.view];
        translation = CGPointMake(-translation.x, translation.y);
        CGPoint desiredPos = CGPointSubtract(_mapNode.position, translation);
        NSLog(@"Moving map to x: %f y: %f", desiredPos.x, desiredPos.y);
        NSLog(@"Map node position x: %f y: %f", _mapNode.position.x, _mapNode.position.y);
        NSLog(@"Map scale is %f", mapScale);
        NSLog(@"Map size is x: %f y: %f", _mapNode.map.frame.size.width, _mapNode.map.frame.size.height);

        if (desiredPos.y <= (mapScale * 300) && desiredPos.y >= ((1/mapScale) * 200)) {
            _mapNode.position = CGPointMake(_mapNode.position.x, desiredPos.y);
            [recognizer setTranslation:CGPointZero inView:recognizer.view];
        }

        if (desiredPos.x <= (mapScale * 250) && desiredPos.x >= ((1/mapScale) * 77)) {
            _mapNode.position = CGPointMake(desiredPos.x, _mapNode.position.y);
            [recognizer setTranslation:CGPointZero inView:recognizer.view];
        }
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {

    }
}

我在缩放时设置了比例iVar以获得节点的比例。我应该可以使用节点的大小(_mapNode.mapSKSpriteNode)和屏幕大小来获得我想要的平移。

我以为我可以做scale*xMax(1/scale)*xMin(也有y位置),但这似乎不起作用。我希望在那里没有硬数字(300,200等)并使用节点/屏幕/等的大小来限制平移。任何帮助表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:0)

好的,这就是我为人们未来的参考做的。

我首先创建了两个iVar:一个用于节点的初始x位置,另一个用于初始y位置。然后我通过:sizeOfNode * 0.5 * scale并减去screenSize * 0.5来计算“可移动距离”。只要desiredLocation <= (initialPos + movableDistance)desiredLocation >= (initialPos - moveableDistance),您就可以更改节点的位置。您可以为x和y执行此操作。