Sprite Kit - Determine vector of swipe gesture to flick sprite

后端 未结 3 1739
感动是毒
感动是毒 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条回答
  •  Happy的楠姐
    2021-02-02 04:19

    Here's an example of how to detect a swipe gesture:

    First, define instance variables to store the starting location and time .

        CGPoint start;
        NSTimeInterval startTime;
    

    In touchesBegan, save the location/time of a touch event.

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        /* Avoid multi-touch gestures (optional) */
        if ([touches count] > 1) {
            return;
        }
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInNode:self];
        // Save start location and time
        start = location;
        startTime = touch.timestamp;
    }
    

    Define parameters of the swipe gesture. Adjust these accordingly.

    #define kMinDistance    25
    #define kMinDuration    0.1
    #define kMinSpeed       100
    #define kMaxSpeed       500
    

    In touchesEnded, determine if the user's gesture was a swipe by comparing the differences between starting and ending locations and time stamps.

    - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInNode:self];
        // Determine distance from the starting point
        CGFloat dx = location.x - start.x;
        CGFloat dy = location.y - start.y;
        CGFloat magnitude = sqrt(dx*dx+dy*dy);
        if (magnitude >= kMinDistance) {
            // Determine time difference from start of the gesture
            CGFloat dt = touch.timestamp - startTime;
            if (dt > kMinDuration) {
                // Determine gesture speed in points/sec
                CGFloat speed = magnitude / dt;
                if (speed >= kMinSpeed && speed <= kMaxSpeed) {
                    // Calculate normalized direction of the swipe
                    dx = dx / magnitude;
                    dy = dy / magnitude;
                    NSLog(@"Swipe detected with speed = %g and direction (%g, %g)",speed, dx, dy);
                }
            }
        }
    }
    

提交回复
热议问题