ios - 来自轻弹 Action 和 UIPanGestureRecognizer 的意外结果

标签 ios objective-c uigesturerecognizer sprite-kit uipangesturerecognizer

我正在使用以下代码在 SpriteKit SKScene 中实现 Sprite 的轻弹,因此它们将根据来自 UIPanGestureRecognizer 的手指运动继续在屏幕上移动和滑动。

在大多数情况下它工作正常,但是当我靠近屏幕可视区域的边缘并尝试使用此手势将 Sprite 弹到屏幕外时,它会产生相反的效果并将 Sprite 推回中心而不是屏幕外.

谁能告诉我为什么当 Sprite 太靠近屏幕边缘时它会被推回而不是按预期轻弹屏幕外?

if (recognizer.state == UIGestureRecognizerStateEnded) {
    if ([touchedNode.name isEqualToString:@"sprite"]) {
        SKSpriteNode *touchedSprite = (SKSpriteNode *)touchedNode;
        // Calculate the length of the velocity vector (i.e. the magnitude)
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
        CGFloat slideMult = magnitude / 200;
        NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

        // Calculate a final point based on the above
        float slideFactor = 0.1 * slideMult;    // Increase for more of a slide
        CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor), recognizer.view.center.y - (velocity.y * slideFactor));

        SKAction *moveAction = [SKAction moveTo:finalPoint duration:slideFactor * 2];
        [moveAction setTimingMode:SKActionTimingEaseOut];
        [touchedSprite runAction:moveAction];
    }
}

最佳答案

我认为您可能忘记将 CGPoint 从 View 转换为场景

假设我们初始化了我们的手势

__weak IBOutlet SKView      *skView;
...
panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[skView addGestureRecognizer:panRecognizer];

所以如果我们想在 SpriteKit 空间中有这个手势识别器的触摸位置,我们必须将这个点从 view 转换为 skScene
- (void)handlePan:(UIPanGestureRecognizer*)sender{

CGPoint point = [sender locationInView:skView];
point = [skView.scene convertPointFromView:point];

// do your things here

}

关于ios - 来自轻弹 Action 和 UIPanGestureRecognizer 的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20741711/

相关文章:

ios - 如何在同一位置读取和写入 xml 文件?

ios - UIPrintInteractionController 打印到多台 AirPrint 打印机

objective-c - NSPredicate 中的减法

objective-c - 删除 NSArray 中所有重复的字符串

ios - 检测 UITextView 上的点击仅检测取消

ios - UIView 与 UITableView 和 UIGestureRecognizer 突然停止手势识别

ios - 有关iOS应用开发的基本问题

ios - 使用大标题时如何将导航标题左对齐?

iphone - 使用 block 将NSDictionary转换为字符串?

swift - 点击事件不会在动画 ImageView 上触发