简体   繁体   中英

Moving two different objects with two fingers SpriteKit

I want to move two different objects with two fingers . The problem is that I can't use touchBegan method because of I can't recognize which object I currently operate. The best way is to use gesture recognizers because of I can recognize view that I currently dragging, I can move two or more different objects and I always have refference to them. But I can't use gesture recognizers with SpriteKit.I can't add gestures to my objects but I can add gestures to main SKView , but it will work only with one touch object. So, the question is how can i move two different objects with SpriteKit ?

The touches... methods sure can be used for this. Just for example, to pan multiple sprites, first iterate over the touches. For each one, ask the scene for all the nodes at that point. (This is node you can get a reference to your objects)

Then iterate over all the nodes at that point. If they pass some sort of movability test (lets say by name) use arithmetic to determine their new positions based on the current and previous touch locations of the UITouch object. That being said, the code below will move any sprite on your scene with the name "nameOfMovableObject" along with the touch at that location.

CG_INLINE CGPoint CGPointFromPreviousCoords(CGPoint affectedPoint, CGPoint currentPoint, CGPoint previousPoint) {
    return CGPointMake(affectedPoint.x + currentPoint.x - previousPoint.x, affectedPoint.y + currentPoint.y - previousPoint.y);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];
        CGPoint previousLocation = [touch previousLocationInNode:self];

        for (SKNode *node in [self nodesAtPoint:location]) {
            if ([node.name isEqualToString:@"nameOfMovableObject"]) {
                [node setPosition:CGPointFromPreviousCoords(node.position, location, previousLocation)];
            }
        }
    }
}

我通过将SKViews添加到-(void)didMoveToView:方法来解决此问题,并向此SKViews添加标准UIGestureRecognizes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM