Sprite Kit - Determine vector of swipe gesture to flick sprite

后端 未结 3 1677
感动是毒
感动是毒 2021-02-02 04:14

I have a game where circular objects shoot up from the bottom of the screen and I would like to be able to swipe them to flick them in the direction of my swipe. My issue is, I

3条回答
  •  执念已碎
    2021-02-02 04:43

    There is another way to do it, you can add a pan gesture and then get the velocity from it:

    First add pan gesture in your view:

    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
        [self.view addGestureRecognizer:gestureRecognizer];
    

    Then handle the gesture:

    - (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer
    {
        if (recognizer.state == UIGestureRecognizerStateBegan) {
            CGPoint location = [recognizer locationInView:recognizer.view];
            if ([_object containsPoint:location]){
                self.movingObject = YES;
                <.. object start moving ..>
            }
    
        } else if (recognizer.state == UIGestureRecognizerStateChanged) {
    
            if (!self.movingObject)
                return;
    
            CGPoint translation = [recognizer translationInView:recognizer.view];
            object.position = CGPointMake(object.position.x + translation.x, object.position.y + translation.y);
    
            [recognizer setTranslation:CGPointZero inView:recognizer.view];
    
        } else if (recognizer.state == UIGestureRecognizerStateEnded) {
    
            if (!self.movingObject)
                return;
    
            self.movingObject = NO;
            float force = 1.0f;
            CGPoint gestureVelocity = [recognizer velocityInView:recognizer.view];
            CGVector impulse = CGVectorMake(gestureVelocity.x * force, gestureVelocity.y * force);
    
            <.. Move object with that impulse using an animation..>
        }
    }
    

提交回复
热议问题