ios – Sprite Kit – 确定滑动精灵的滑动手势向量

前端之家收集整理的这篇文章主要介绍了ios – Sprite Kit – 确定滑动精灵的滑动手势向量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个游戏,圆形物体从屏幕底部向上射击,我希望能够滑动它们以向我的滑动方向轻弹它们.我的问题是,我不知道如何计算滑动的矢量/方向,以便使圆形物体以适当的速度在正确的方向上被轻弹.

我正在使用的静态矢量“(5,5)”需要通过滑动的滑动速度和方向来计算.此外,我需要确保一旦我第一次接触到对象,就不再发生这种情况,以避免双重击中对象.这是我目前正在做的事情:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

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

    SKNode* node = [self nodeAtPoint:location];
    [node.physicsBody applyImpulse:CGVectorMake(5,5) atPoint:location];
}
}

解决方法

以下是如何检测滑动手势的示例:

首先,定义实例变量以存储起始位置和时间.

CGPoint start;
    NSTimeInterval startTime;

在touchesBegan中,保存触摸事件的位置/时间.

-(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 kMinDistance    25
#define kMinDuration    0.1
#define kMinSpeed       100
#define kMaxSpeed       500

在touchesEnded中,通过比较起始位置和结束位置与时间戳之间的差异来确定用户的手势是否是滑动.

- (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);
            }
        }
    }
}

猜你在找的iOS相关文章